Jon Jagger
jon@jaggersoft.com
Table of Contents 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Notes DownloadECMA-334 C# Language Specificationpreviousnextprevious at this levelnext at this level 17 Classesprevious at this levelnext at this level 17.4 Fieldsprevious at this levelnext at this level 17.4.5 Variable initializersprevious at this levelnext at this level 17.4.5.1 Static field initialization Paragraph 11 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. 2 If a static constructor (§17.11) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. 3 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:
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 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]
{ JSL }
Jagger Software Ltd
Company # 4070126
VAT # 762 5213 42
Valid HTML 4.01Valid CSS