Calling the base class constructor

suggest change

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

Feedback about page:

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


Constructors and Finalizers:
* Calling the base class constructor

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
38 Constructors and Finalizers
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script