X hits on this document





227 / 396


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.

It is possible for static fields with variable initializers to be observed in their default value state. However, this is strongly discouraged as a matter of style. The example

using 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 output

a = 1, b = 2

because the static fields a and b are initialized to 0 (the default value for int) 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. Static field initialization

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 (§‎10.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 field of that class. 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 { public static int X = Test.F("Init A"); }

class B { public static int Y = Test.F("Init B"); }

might produce either the output:

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

Document info
Document views1111
Page views1111
Page last viewedMon Jan 16 22:36:06 UTC 2017