Calling the base class constructor

Download c# eBook

Example

A constructor of a base class is called before a constructor of a derived class is executed. For example, if Mammal extends Animal, then the code contained in the constructor of Animal is called first when creating an instance of a Mammal.

If a derived class doesn't explicitly specify which constructor of the base class should be called, the compiler assumes the parameterless constructor.

public class Animal
{
    public Animal() { Console.WriteLine("An unknown animal gets born."); }
    public Animal(string name) { Console.WriteLine(name + " gets born"); }
}

public class Mammal : Animal
{
    public Mammal(string name)
    {
        Console.WriteLine(name + " is a mammal.");
    }
}

In this case, instantiating a Mammal by calling new Mammal("George the Cat") will print

An unknown animal gets born.
George the Cat is a mammal.

View Demo

Calling a different constructor of the base class is done by placing : base(args) between the constructor's signature and its body:

public class Mammal : Animal
{
    public Mammal(string name) : base(name)
    {
        Console.WriteLine(name + " is a mammal.");
    }
}

Calling new Mammal("George the Cat") will now print:

George the Cat gets born.
George the Cat is a mammal.

View Demo

Stats

Contributors: 4
2016-08-10
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook