X hits on this document

959 views

0 shares

0 downloads

0 comments

266 / 396

Chapter ‎18   Unsafe code

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 = 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; 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). 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 { int x, y, count;

Copyright Microsoft Corporation 1999-2003. All Rights Reserved.253

Document info
Document views959
Page views959
Page last viewedThu Dec 08 12:44:09 UTC 2016
Pages396
Paragraphs9401
Words133190

Comments