C# Constructors and Inheritance

In this chapter you will learn:

  1. C# Constructors and Inheritance
  2. Note for 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,


//  w w  w  .  j a v  a2s. co 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  . jav  a 2  s . c o m
  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.

Next chapter...

What you will learn in the next chapter:

  1. What are destructors
  2. Syntax for C# Destructor
  3. Example for C# Destructor
  4. Destructor calling sequence
  5. Update static field in the deconstructor
  6. How to Base destructor got called from child destructor
Home »
  C# Tutorial »
    C# Types »
      C# Constructor
C# Constructor
C# Default constructors
C# Constructor's Parameters
C# Constructor Overload
C# Static Constructors
C# Constructors and Inheritance