CSharp - Constructors and Inheritance


A subclass must declare its own constructors.

The base class's constructors are accessible to the derived class, but not inherited.

For example, if we define Baseclass and Subclass as follows:

class Baseclass
       public int X;
       public Baseclass () { }
       public Baseclass (int x) { this.X = x; }

class Subclass : Baseclass { 


the following is illegal:

Subclass s = new Subclass (123);

Subclass must define its own constructors.

It can call any of the base class's constructors with the base keyword:

class Subclass : Baseclass
       public Subclass (int x) : base (x) { }

base keyword calls a constructor in the base class.

Base-class constructors always execute first to ensure that base initialization occurs before specialized initialization.

Related Topics