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.

<strong>C#</strong> LANGUAGE SPECIFICATIONusing System;class A{public static int X;static A() { X = B.Y + 1;}}class B{public static int Y = A.X + 1;static B() {}static void Main() {Console.WriteLine("X = {0}, Y = {1}", A.X, B.Y);}}produces the outputX = 1, Y = 2To execute the Main method, the system first runs the initializer for B.Y, prior to class B's static constructor.Y's initializer causes A's static constructor to be run because the value of A.X is referenced. The static constructorof A in turn proceeds to compute the value of X, and in doing so fetches the default value of Y, which is zero. A.Xis thus initialized to 1. The process of running A's static field initializers and static constructor then completes,returning to the calculation of the initial value of Y, the result of which becomes 2. end example]17.12 DestructorsA destructor is a member that implements the actions required to destruct an instance of a class. A destructor isdeclared using a destructor-declaration:destructor-declaration:attributes opt extern opt ~ identifier ( ) destructor-bodydestructor-body:block;A destructor-declaration may include a set of attributes (§24).The identifier of a destructor-declarator must name the class in which the destructor is declared. If any othername is specified, a compile-time error occurs.When a destructor declaration includes an extern modifier, the destructor is said to be an external destructor.Because an external destructor declaration provides no actual implementation, its destructor-body consists of asemicolon. For all other destructors, the destructor-body consists of a block, which specifies the statements toexecute in order to destruct an instance of the class. A destructor-body corresponds exactly to the method-body ofan instance method with a void return type (§17.5.8).Destructors are not inherited. Thus, a class has no destructors other than the one which may be declared in thatclass.[Note: Since a destructor is required to have no parameters, it cannot be overloaded, so a class can have, at most,one destructor. end note]Destructors are invoked automatically, and cannot be invoked explicitly. An instance becomes eligible fordestruction when it is no longer possible for any code to use that instance. Execution of the destructor for theinstance may occur at any time after the instance becomes eligible for destruction. When an instance isdestructed, the destructors in that instance’s inheritance chain are called, in order, from most derived to leastderived [Example: The output of the example264

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

Saved successfully!

Ooh no, something went wrong!