C# Constructors and Inheritance
Description
A subclass must declare its own constructors.
Subclass must redefine any constructors it wants to expose.
It can call any of the base class's constructors with the base keyword.
For example,
/*from w w w . ja v a 2s . c o m*/
public class Baseclass
{
public int X;
public Baseclass () { }
public Baseclass (int x) { this.X = x; }
}
public class Subclass : Baseclass
{
public Subclass (int x) : base (x) { }
}
Note
The base keyword works rather like the this keyword, except that it calls a constructor in the base class.
Base class constructors always execute first; this ensures that base initialization occurs before specialized initialization.
For Implicit calling of the parameterless base class constructor. If a constructor in a subclass omits the base keyword, the base type's parameter-less constructor is implicitly called:
public class BaseClass
{/*from w w w . j a v a 2s. c om*/
public int X;
public BaseClass() { X = 1; }
}
public class Subclass : BaseClass
{
public Subclass() { Console.WriteLine (X); } // 1
}
If the base class has no parameterless constructor, subclasses are forced to use the base keyword in their constructors.