Thursday 9 May 2019

Initialization before instantiation

Are you telling me that I can initialize a class without running the default constructor? and why on earth would I want to do this?

the answer is yes you can and when you're unit testing.

Within the system.runtime.serialization namespace there's a static FormatterServices class with a GetUnitializedObject(Type) method, this method lets you create a new instance of an object without constructing it.


using System;
using System.Runtime.Serialization;

namespace pav.InitializationB4Instantiation
{
    class Dog 
    {
        string name;
        public string Name {
            get => name ?? "Spot";
            set => name = value;
        }

        public Dog() => Console.WriteLine($"Name: {Name}");
    }

    class Program
    {
        static void Main(string[] args)
        {
            //Create instance of dog without instantiating the object
            var dog = FormatterServices.GetUninitializedObject(typeof(Dog));

            //get an instance of the parameterless constructor of Dog
            var dogCtor = typeof(Dog).GetConstructor(Type.EmptyTypes);

            //Set the Name property to "Fluffy" 
            ((Dog)dog).Name = "Fluffy";
           
            //instantiate Dog
            dogCtor.Invoke(dognull);

            //instantiate a default dog
            new Dog();
        }
    }
}



and this is what results



Obviously this is an extremely contrived example, but the take away is that you can modify the classes properties before "newing" up an instance of it which can be vary useful when unit testing code.