Field Initialisers vs Constructor Initialisers

Hmmmm, I like Field Initialisers in C#, but I also like Constructor Initialisers in C#. But which is better? There’s only one way to find out…FIGHT!

Well, actually, no. Here is some C# code to compare them. I was interested as to what fired first:

    //This is the class we will use to test field vs constructor initialisers
    //Write out to the console when the constructor is called.
    class FieldInitTest
    {
        public FieldInitTest(string number)
        {
            Console.WriteLine(number);
        }
    }

    //This class will perform our field vs constructor initialiser test
    class FieldInitTester
    {
        public FieldInitTest fieldInitTest1;
        public FieldInitTest fieldInitTest2 = new FieldInitTest("2");
        public FieldInitTester()
        {
            fieldInitTest1 = new FieldInitTest("1");
        }
    }

    //run the test
    static void Main(string[] args)
    {
        FieldInitTester fit = new FieldInitTester();
    }

When run, the output is shown below:

Field and Constructor Initialiser - Results

So there we have it, field initialisers are run before constructor ones. As to which is better…I’ll leave that up to you.

Leave a Reply