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 initializers Paragraph 11 Field declarations may include variable-initializers. 2 For static fields, variable initializers correspond to assignment statements that are executed during class initialization. 3 For instance fields, variable initializers correspond to assignment statements that are executed when an instance of the class is created. [Example: The example
using System;  
class Test  
{  
   static double x = Math.Sqrt(2.0);  
   int i = 100;  
   string s = "Hello";  
   static void Main() {  
      Test a = new Test();  
      Console.WriteLine("x = {0}, i = {1}, s = {2}", x, a.i, a.s);  
   }  
}  
produces the output
x = 1.4142135623731, i = 100, s = Hello  
because an assignment to x occurs when static field initializers execute and assignments to i and s occur when the instance field initializers execute. end example]
Paragraph 21 The default value initialization described in §17.4.3 occurs for all fields, including fields that have variable initializers. 2 Thus, when a class is initialized, all static fields in that class are first initialized to their default values, and then the static field initializers are executed in textual order. 3 Likewise, when an instance of a class is created, all instance fields in that instance are first initialized to their default values, and then the instance field initializers are executed in textual order. Paragraph 31 It is possible for static fields with variable initializers to be observed in their default value state. [Example: However, this is strongly discouraged as a matter of style. The example
using System;  
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 valid. It results in the output
a = 1, b = 2  
because the static fields a and b are initialized to 0 (the default value for int) before their initializers are executed. When the initializer for a runs, the value of b is zero, and so a is initialized to 1. When the initializer for b runs, the value of a is already 1, and so b is initialized to 2. end example]
{ JSL }
Jagger Software Ltd
Company # 4070126
VAT # 762 5213 42
Valid HTML 4.01Valid CSS