13.07.2015 Views

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 17 Classes}static void Main() {Test a = new Test();Console.WriteLine("x = {0}, i = {1}, s = {2}", x, a.i, a.s);}produces the outputx = 1.4142135623731, i = 100, s = Hellobecause an assignment to x occurs when static field initializers execute and assignments to i and s occur whenthe instance field initializers execute. end example]The default value initialization described in §17.4.3 occurs for all fields, including fields that have variableinitializers. 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 initializersare executed in textual order.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 exampleusing 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 outputa = 1, b = 2because the static fields a and b are initialized to 0 (the default value for int) before their initializers areexecuted. When the initializer for a runs, the value of b is zero, and so a is initialized to 1. When the initializerfor b runs, the value of a is already 1, and so b is initialized to 2. end example]17.4.5.1 Static field initializationThe static field variable initializers of a class correspond to a sequence of assignments that are executed in thetextual order in which they appear in the class declaration. If a static constructor (§17.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 fieldof that class. [Example: The exampleusing 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");}225

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!