Create Type Instance without invoking constructor
Wednesday, July 9th, 2008It is not a secret that deserialization in .NET creates class instances without invoking constructor. This is wierd but somethimes it may be helpful, for example in unit testing.
Fortunatelly it is possible to access this functionality from client code:
class my
{
public my()
{
Console.WriteLine(“Constructor”);
}
}
class Program{
static void Main(string[] args)
{
my withConstructor = new my();
my m = (my)FormatterServices.GetUninitializedObject(typeof(my));
. . .
FormatterServices class form System.Runtime.Serialization namespace is able to instantiate instance of classes without invoking its constructor.