Static field initializers run just beforethe static constructor is called. If a type has no
static constructor, field initializers will execute just prior to the type being used—
or anytime earlierat the whim of the runtime. (This means that the presence of a
static constructor may cause field initializers to execute later in the program than
they would otherwise.)
Static field initializers run in the order in which the fields are declared. The following
example illustrates this: Xis initialized to 0 and Yis initialized to 3.
1 class Foo 2 { 3 public static int X = Y; // 0 4 public static int Y = 3; // 3 5 }
If we swap the two field initializers around, both fields are initialized to 3. The next
example prints 0 followed by 3 because the field initializer that instantiates a Foo
executes before Xis initialized to 3:
1 class Program 2 { 3 static void Main() { Console.WriteLine (Foo.X); } // 3 4 } 5 class Foo 6 { 7 public static Foo Instance = new Foo(); 8 public static int X = 3; 9 Foo() { Console.WriteLine (X); } // 0 10 }
If we swap the two lines in boldface, the example prints 3 followed by 3.