C# Language Constructors and Finalizers Calling the base class constructor

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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



Got any C# Language Question?