13.07.2015 Views

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>C#</strong> LANGUAGE SPECIFICATIONclass B{public static int Y = Test.f("Init B");}might produce either the output:Init AInit B1 1or the output:Init BInit A1 1because the execution of X's initializer and Y's initializer could occur in either order; they are only constrained tooccur 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 BInit A1 1because the rules for when static constructors execute provide that B's static constructor (and hence B's static fieldinitializers) must run before A's static constructor and field initializers. end example]17.4.5.2 Instance field initializationThe instance field variable initializers of a class correspond to a sequence of assignments that are executedimmediately upon entry to any one of the instance constructors (§17.10.2) of that class. The variable initializersare executed in the textual order in which they appear in the class declaration. The class instance creation andinitialization process is described further in §17.10.A variable initializer for an instance field cannot reference the instance being created. Thus, it is a compile-timeerror to reference this in a variable initializer, as it is a compile-time error for a variable initializer to referenceany instance member through a simple-name. [Example: In the exampleclass A{int x = 1;}int y = x + 1;// Error, reference to instance member of this226

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

Saved successfully!

Ooh no, something went wrong!