When are Constructors Called?


In the foregoing discussion of inheritance and class hierarchies, an important question may have occurred to you: When a derived class object is created, whose constructor is executed first? The one in the derived class or the one defined by the base class? For example, given a derived class called B and a base class called A, is A’s constructor called before B’s, or vice versa? The answer is that in a class hierarchy, constructors are called in order of derivation, from base class to derived class. Furthermore, this order is the same whether or not base is used. If base is not used, then the default (parameterless) constructor of each base class will be executed. The following program illustrates the order of constructor execution:

 // Demonstrate when constructors are called. using System; // Create a base class. class A {   public A() {     Console.WriteLine("Constructing A.");   } } // Create a class derived from A. class B : A {   public B() {     Console.WriteLine("Constructing B.");   } } // Create a class derived from B. class C : B {   public C() {     Console.WriteLine("Constructing C.");   } } class OrderOfConstruction {   public static void Main() {     C c = new C();   } }

The output from this program is shown here:

 Constructing A. Constructing B. Constructing C.

As you can see, the constructors are called in order of derivation.

If you think about it, it makes sense that constructors are executed in order of derivation. Because a base class has no knowledge of any derived class, any initialization it needs to perform is separate from and possibly prerequisite to any initialization performed by the derived class. Therefore, its constructor must be executed first.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net