Export (0) Print
Expand All

10.4.5.1 Static field initialization

Visual Studio .NET 2003

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 (Section 10.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. 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:

Init A
Init B
1 1

or the output:

Init B
Init A
1 1

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:

Init B
Init A
1 1

because the rules for when static constructors execute (as defined in Section 10.11) provide that B's static constructor (and hence B's static field initializers) must run before A's static constructor and field initializers.

Show:
© 2014 Microsoft