X hits on this document





226 / 396

Chapter ‎18   Unsafe code

the field finished to be set to true, then reads the field result. Since finished has been declared volatile, the main thread must read the value 143 from the field result. If the field finished had not been declared volatile, then it would be permissible for the store to result to be visible to the main thread after the store to finished, and hence for the main thread to read the value 0 from the field result. Declaring finished as a volatile field prevents any such inconsistency.

10.4.4 Field initialization

The initial value of a field, whether it be a static field or an instance field, is the default value (§‎5.2) of the field’s type. It is not possible to observe the value of a field before this default initialization has occurred, and a field is thus never “uninitialized”. The example

using System;

class Test { static bool b; int i;

static void Main() { Test t = new Test(); Console.WriteLine("b = {0}, i = {1}", b, t.i); } }

produces the output

b = False, i = 0

because b and i are both automatically initialized to default values.

10.4.5 Variable initializers

Field declarations may include variable-initializers. 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.

The example

using System;

class Test { static double x = Math.Sqrt(2.0); int i = 100; string s = "Hello";

static void Main() { Test a = new Test(); Console.WriteLine("x = {0}, i = {1}, s = {2}", x, a.i, a.s); } }

produces the output

x = 1.4142135623731, i = 100, s = Hello

because an assignment to x occurs when static field initializers execute and assignments to i and s occur when the instance field initializers execute.

The default value initialization described in §‎10.4.4 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

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

Document info
Document views452
Page views452
Page last viewedSun Oct 23 01:44:13 UTC 2016