How does static field initialization work in C#?

This is correct.

Your static initializers, then the static constructor is run before your standard constructor, but when it runs, it’s using new A(), so passing through your non-static constructor path. This causes the messages you see.

Here is the full path of execution:

When you first call var a = new A(); in your program, this is the first time A is accessed.

This will fire off the static initialization of A._A

At this point, A._A constructs with _A = (new A()).I();

This hits


Console.WriteLine("new A()");
if (_A == null)
    Console.WriteLine("_A == null");        

since at this point, _A hasn’t been set with the returned, constructed type (yet).

Next, the static constructor A { static A(); } is run. This prints the “static A()” message.

Finally, your original statement (var a = new A();) is executed, but at this point, the statics are constructed, so you get the final print.

Leave a Comment