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 SPECIFICATION}static void Main() {finished = false;// Run Thread2() in a new threadnew Thread(new ThreadStart(Thread2)).Start();// Wait for Thread2 to signal that it has a result by setting// finished to true.for (;;) {if (finished) {Console.WriteLine("result = {0}", result);return;}}}produces the output:result = 143In this example, the method Main starts a new thread that runs the method Thread2. This method stores a valueinto a non-volatile field called result, then stores true in the volatile field finished. The main thread waitsfor the field finished to be set to true, then reads the field result. Since finished has been declaredvolatile, the main thread must read the value 143 from the field result. If the field finished had not beendeclared volatile, then it would be permissible for the store to result to be visible to the main thread afterthe store to finished, and hence for the main thread to read the value 0 from the field result. Declaringfinished as a volatile field prevents any such inconsistency. end example]17.4.4 Field initializationThe initial value of a field, whether it be a static field or an instance field, is the default value (§12.2) of thefield’s type. It is not possible to observe the value of a field before this default initialization has occurred, and afield is thus never “uninitialized”. [Example: The exampleusing 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 outputb = False, i = 0because b and i are both automatically initialized to default values. end example]17.4.5 Variable initializersField declarations may include variable-initializers. For static fields, variable initializers correspond toassignment statements that are executed during class initialization. For instance fields, variable initializerscorrespond to assignment statements that are executed when an instance of the class is created.[Example: The exampleusing System;class Test{static double x = Math.Sqrt(2.0);int i = 100;string s = "Hello";224

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

Saved successfully!

Ooh no, something went wrong!