Calling the base class constructor

suggest change

A base constructor runs before the body of the derived constructor. For example, if Mammal derives from Animal, the Animal constructor runs first when you create a Mammal.

If a derived constructor does not say which base constructor to call, the compiler uses the parameterless one. The base class must have that 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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents