Static field initialization
The static field variable initializersof 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 (§10.12) 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. The example using System; class Test public static int F(string s) { class A class B might produce either the output: Init A or the output: Init B 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 public static int F(string s) { class A public static int X = Test.F("Init A"); class B public static int Y = Test.F("Init B"); the output must be: Init B because the rules for when static constructors execute (as defined in §10.12) provide that B’s static constructor (and hence B’s static field initializers) must run before A’s static constructor and field initializers.
|