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 SPECIFICATIONusing System;class A{public A() {PrintFields();}public virtual void PrintFields() {}}class B: A{int x = 1;int y;public B() {y = -1;}public override void PrintFields() {Console.WriteLine("x = {0}, y = {1}", x, y);}}When new B() is used to create an instance of B, the following output is produced:x = 1, y = 0The value of x is 1 because the variable initializer is executed before the base class instance constructor isinvoked. However, the value of y is 0 (the default value of an int) because the assignment to y is not executeduntil after the base class constructor returns.It is useful to think of instance variable initializers and constructor initializers as statements that are automaticallyinserted before the constructor-body. The exampleusing System;using System.Collections;class A{int x = 1, y = -1, count;}public A() {count = 0;}public A(int n) {count = n;}class B: A{double sqrt2 = Math.Sqrt(2.0);ArrayList items = new ArrayList(100);int max;public B(): this(100) {items.Add("default");}public B(int n): base(n – 1) {max = n;}}contains several variable initializers; it also contains constructor initializers of both forms (base and this). Theexample corresponds to the code shown below, where each comment indicates an automatically insertedstatement (the syntax used for the automatically inserted constructor invocations isn’t valid, but merely serves toillustrate the mechanism).using System.Collections;260

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

Saved successfully!

Ooh no, something went wrong!