ECMA-334 C# Language Specification17.4.5.1: Static field initialization |
The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. If a static constructor (17.11) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class. [Example: The example
using System;
class Test
{
static void Main() {
Console.WriteLine("{0} {1}", B.Y, A.X);
}
public static int f(string s) {
Console.WriteLine(s);
return 1;
}
}
class A
{
public static int X = Test.f("Init A");
}
class B
{
public static int Y = Test.f("Init B");
}
|
might produce either the output: or the output: because the execution of X's initializer and Y's initializer could occur in either order; they are only constrained to occur before the references to those fields. However, in the example:
using System;
class Test {
static void Main() {
Console.WriteLine("{0} {1}", B.Y, A.X);
}
public static int f(string s) {
Console.WriteLine(s);
return 1;
}
}
class A
{
static A() {}
public static int X = Test.f("Init A");
}
class B
{
static B() {}
public static int Y = Test.f("Init B");
}
|
the output must be: because the rules for when static constructors execute provide that B's static constructor (and hence B's static field initializers) must run before A's static constructor and field initializers. end example]