It is possible to construct circular dependencies that allow static fields with variable initializers to be observed in their default value state.
The example
class A { public static int X = B.Y + 1; } class B { public static int Y = A.X + 1; static void Main() { Console.WriteLine("X = {0}, Y = {1}", A.X, B.Y); } }
produces the output
X = 1, Y = 2
To execute the Main
method, the system first loads class B
. The static constructor of B
proceeds to compute the initial value of Y
, which recursively causes A
to be loaded because the value of A.X
is referenced. The static constructor of A
in turn proceeds to compute the initial value of X
, and in doing so fetches the default value of Y
, which is zero. A.X
is thus initialized to 1
. The process of loading A
then completes, returning to the calculation of the initial value of Y
, the result of which becomes 2
.
Had the Main
method instead been located in class A
, the example would have produced the output
X = 2, Y = 1
Circular references in static field initializers should be avoided since it is generally not possible to determine the order in which classes containing such references are loaded.