Field declarations may include variable-initializers. For static fields, variable initializers correspond to assignment statements that are executed when the class is loaded. For instance fields, variable initializers correspond to assignment statements that are executed when an instance of the class is created.
The example
class Test { static double x = Math.Sqrt(2.0); int i = 100; string s = "Hello"; static void Main() { Test t = new Test(); Console.WriteLine("x = {0}, i = {1}, s = {2}", x, t.i, t.s); } }
produces the output
x = 1.414213562373095, i = 100, s = Hello
because an assignment to x
occurs when the class is loaded and assignments to i
and s
occur when an new instance of the class is created.
The default value initialization described in §10.4.3 occurs for all fields, including fields that have variable initializers. Thus, when a class is loaded, all static fields are first initialized to their default values, and then the static field initializers are executed in textual order. Likewise, when an instance of a class is created, all instance fields are first initialized to their default values, and then the instance field initializers are executed in textual order.
It is possible for static fields with variable initializers to be observed in their default value state, though this is strongly discouraged as a matter of style. The example
class Test { static int a = b + 1; static int b = a + 1; static void Main() { Console.WriteLine("a = {0}, b = {1}, a, b); } }
exhibits this behavior. Despite the circular definitions of a and b, the program is legal. It produces the output
a = 1, b = 2