Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is called first static constructor or private constructor

Tags:

c#

I was reading a tutorial for implementing Singleton and the code is

public class Singleton
    {
        private static readonly Singleton instance = new Singleton();

        static Singleton()
        {
            Console.WriteLine("Static");
        }
        private Singleton()
        {
            Console.WriteLine("Private");
        }

        public static Singleton Instance { get { return instance; } }

        public void DoSomething() {
            //this must be thread safe
        }
    }

When I write Singleton.Instance, the output is

Private
Static

I was expecting it to be

Static
Private

Reason being that when I read a MSDN tutorial "https://msdn.microsoft.com/en-us/library/k9x6w0hc.aspx"

I saw that public constructor was called after the static constructor.

Why is there a difference?

like image 405
Rajat Avatar asked Feb 14 '17 05:02

Rajat


1 Answers

The static constructor has to complete before code outside the class can use the class. But the language specification has to allow the instance constructor to complete before the static constructor does, so that you could e.g. do this:

static Singleton()
{
    instance = new Singleton();
    // It has to be legal to use "instance" here
    Console.WriteLine("Static");
}

Note that in your example, that's essentially what happens anyway. Field initializers essentially become part of the constructor; they just execute first.

This is corroborated by the generated IL:

// Static constructor
Singleton..cctor:
IL_0000:  newobj      Singleton..ctor     //Calls private constructor first
IL_0005:  stsfld      Singleton.instance  //to create .instance
IL_000A:  nop         
IL_000B:  ldstr       "Static"
IL_0010:  call        System.Console.WriteLine
IL_0015:  nop         
IL_0016:  ret         

See also related (but not duplicate) question and Eric Lippert's typically excellent answer here: Calling of Static Constructor and Instance Constructor

like image 185
Peter Duniho Avatar answered Oct 28 '22 10:10

Peter Duniho