X hits on this document





228 / 396

Chapter ‎18   Unsafe code

Init A Init B 1 1

or the output:

Init B Init A 1 1

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:

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 B Init A 1 1

because the rules for when static constructors execute (as defined in §‎10.11) provide that B’s static constructor (and hence B’s static field initializers) must run before A’s static constructor and field initializers. Instance field initialization

The instance field variable initializers of a class correspond to a sequence of assignments that are executed immediately upon entry to any one of the instance constructors (§‎10.10.1) of that class. The variable initializers are executed in the textual order in which they appear in the class declaration. The class instance creation and initialization process is described further in §‎10.10.

A variable initializer for an instance field cannot reference the instance being created. Thus, it is a compile-time error to reference this in a variable initializer, as it is a compile-time error for a variable initializer to reference any instance member through a simple-name. In the example

Copyright Microsoft Corporation 1999-2003. All Rights Reserved.215

Document info
Document views449
Page views449
Page last viewedSun Oct 23 01:33:12 UTC 2016