Merge pull request #5714 from alexischr/update_bockbuild
[mono.git] / mcs / docs / ecma334 / 17.4.5.xml
1 <?xml version="1.0"?>
2 <clause number="17.4.5" title="Variable initializers">
3   <paragraph>Field declarations may include <non_terminal where="19.6">variable-initializer</non_terminal>s. For static fields, variable initializers correspond to assignment statements that are executed during class initialization. For instance fields, variable initializers correspond to assignment statements that are executed when an instance of the class is created. </paragraph>
4   <paragraph>
5     <example>[Example: The example <code_example><![CDATA[
6 using System;  
7 class Test  
8 {  
9    static double x = Math.Sqrt(2.0);  
10    int i = 100;  
11    string s = "Hello";  
12    static void Main() {  
13       Test a = new Test();  
14       Console.WriteLine("x = {0}, i = {1}, s = {2}", x, a.i, a.s);  
15    }  
16 }  
17 ]]></code_example>produces the output <code_example><![CDATA[
18 x = 1.4142135623731, i = 100, s = Hello  
19 ]]></code_example>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]</example>
20   </paragraph>
21   <paragraph>The default value initialization described in <hyperlink>17.4.3</hyperlink> occurs for all fields, including fields that have variable initializers. 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. 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>
22   <paragraph>It is possible for static fields with variable initializers to be observed in their default value state. <example>[Example: However, this is strongly discouraged as a matter of style. The example <code_example><![CDATA[
23 using System;  
24 class Test  
25 {  
26    static int a = b + 1;  
27    static int b = a + 1;  
28    static void Main() {  
29       Console.WriteLine("a = {0}, b = {1}", a, b);  
30    }  
31 }  
32 ]]></code_example>exhibits this behavior. Despite the circular definitions of a and b, the program is valid. It results in the output <code_example><![CDATA[
33 a = 1, b = 2  
34 ]]></code_example>because the static fields a and b are initialized to 0 (the default value for <keyword>int</keyword>) 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]</example> </paragraph>
35 </clause>