Constructor execution
Variable initializers are transformed into assignment statements, and these assignment statements are executed before the invocation of the base class instance constructor. This ordering ensures that all instance fields are initialized by their variable initializers before any statements that have access to that instance are executed. Given the example using System; class A public virtual void PrintFields() {} } class B: A public B() { public override void PrintFields() { when new B() is used to create an instance of B, the following output is produced: x = 1, y = 0 The value of x is 1 because the variable initializer is executed before the base class instance constructor is invoked. However, the value of y is 0 (the default value of an int) because the assignment to y is not executed until after the base class constructor returns. It is useful to think of instance variable initializers and constructor initializers as statements that are automatically inserted before the constructor-body. The example using System; class A public A() { public A(int n) { class B: A public B(): this(100) { public B(int n): base(n – 1) { contains several variable initializers; it also contains constructor initializers of both forms (base and this). The example corresponds to the code shown below, where each comment indicates an automatically inserted statement (the syntax used for the automatically inserted constructor invocations isn’t valid, but merely serves to illustrate the mechanism). using System.Collections; class A public A() { public A(int n) { class B: A public B(): this(100) { public B(int n): base(n – 1) {
|