C#: Base Class’ Constructors

When you instantiate a child class by invoking one of its constructors, the first thing the constructor does is call the default constructor (the one that takes no argument) of the direct parent class.

In the parent class, the constructor also calls the constructor of its direct parent class. 

In other words, when you create a child object, all its parent classes are also instantiated.

using System;

namespace DefConstruct
{
    class Program
    {
        class Star
        {
            public Star()
            {
                Console.WriteLine("Star()");
            }
            public Star(string name)
            {
                Console.WriteLine("Star() " + name);
            }
        }

        class Actress : Star
        {
            public Actress(string name)
            {
                Console.WriteLine("Actress() " + name);
            }
        }

        static void Main()
        {
            Actress actress = new Actress("Susan Sarandon");
            Console.ReadKey();
        }
    }
}

The output from running the above code is:

Star()
Actress() Susan Sarandon

Actress is a derived class of Star.  The output proves that the first thing that the Star class’s constructor does is invoke the Star class’s default constructor in line 9 even when there is another constructor with the same set of arguments.

 

 

Series Navigation<< C#: Modifying method behavior in derived class using new keyword
C#: The base keyword in constructor >>