Merge pull request #5714 from alexischr/update_bockbuild
[mono.git] / mcs / docs / ecma334 / 17.4.5.1.xml
1 <?xml version="1.0"?>
2 <clause number="17.4.5.1" title="Static field initialization">
3   <paragraph>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 (<hyperlink>17.11</hyperlink>) 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. <example>[Example: The example <code_example><![CDATA[
4 using System;  
5 class Test   
6 {   
7    static void Main() {  
8       Console.WriteLine("{0} {1}", B.Y, A.X);  
9    }  
10    public static int f(string s) {  
11       Console.WriteLine(s);  
12       return 1;  
13    }  
14 }  
15 class A  
16 {  
17    public static int X = Test.f("Init A");  
18 }  
19 class B  
20 {  
21    public static int Y = Test.f("Init B");  
22 }  
23 ]]></code_example>might produce either the output: <code_example><![CDATA[
24 Init A  
25 Init B  
26 1 1  
27 ]]></code_example>or the output: <code_example><![CDATA[
28 Init B  
29 Init A  
30 1 1  
31 ]]></code_example>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: <code_example><![CDATA[
32 using System;  
33 class Test {  
34    static void Main() {  
35       Console.WriteLine("{0} {1}", B.Y, A.X);  
36    }  
37    public static int f(string s) {  
38       Console.WriteLine(s);  
39       return 1;  
40    }  
41 }  
42 class A  
43 {  
44    static A() {}  
45    public static int X = Test.f("Init A");  
46 }  
47 class B  
48 {  
49    static B() {}  
50    public static int Y = Test.f("Init B");  
51 }  
52 ]]></code_example>the output must be: <code_example><![CDATA[
53 Init B  
54 Init A  
55 1 1  
56 ]]></code_example>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]</example> </paragraph>
57 </clause>