This sample from C# in a Nutshell says it writes 0 followed by 3 due to "the field initializer that instantiates a Foo executes before X is initialized to 3".
class Program {
static void Main() { Console.WriteLine (Foo.X); } // 3
}
class Foo
{
public static Foo Instance = new Foo(); //static field 1
public static int X = 3; //static field 2
Foo() => Console.WriteLine (X); // 0
}
My question is, why does this not go into an infinite recursion due to static field 1 which makes a new Foo (which makes a new Foo, which makes a new Foo, etc.)?
Let's have a look at what's going on. Before
Fooclass addressingstaticfields must be initialized..Net will do it in order they are mentioned in the class declaration:
Instancestart its initializationconstructor
Foo()called which printsX:Foo() => Console.WriteLine (X);note, that sinceXhas not been initialized,0will be printed.Xwill be initialized, it's now3Initialization is completed now, and .Net is ready to adddress
Fooclassand
3will be printed (note the 2nd step of the initialization)