13.07.2015 Views

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 17 ClassesThe identifier of a static-constructor-declaration must name the class in which the static constructor is declared.If any other name is specified, a compile-time error occurs.When a static constructor declaration includes an extern modifier, the static constructor is said to be an externalstatic constructor. Because an external static constructor declaration provides no actual implementation, itsstatic-constructor-body consists of a semicolon. For all other static constructor declarations, the staticconstructor-bodyconsists of a block, which specifies the statements to execute in order to initialize the class. Thiscorresponds exactly to the method-body of a static method with a void return type (§17.5.8).Static constructors are not inherited, and cannot be called directly.The static constructor for a class executes at most once in a given application domain. The execution of a staticconstructor is triggered by the first of the following events to occur within an application domain:• An instance of the class is created.• Any of the static members of the class are referenced.If a class contains the Main method (§10.1) in which execution begins, the static constructor for that classexecutes before the Main method is called. If a class contains any static fields with initializers, those initializersare executed in textual order immediately prior to executing the static constructor.[Example: The exampleusing System;class Test{static void Main() {A.F();B.F();}}class A{static A() {Console.WriteLine("Init A");}public static void F() {Console.WriteLine("A.F");}}class B{static B() {Console.WriteLine("Init B");}public static void F() {Console.WriteLine("B.F");}}must produce the output:Init AA.FInit BB.Fbecause the execution of A's static constructor is triggered by the call to A.F, and the execution of B's staticconstructor is triggered by the call to B.F. end example]It is possible to construct circular dependencies that allow static fields with variable initializers to be observed intheir default value state.[Example: The example263

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

Saved successfully!

Ooh no, something went wrong!