#768 – When to Call the Constructor of a Base Class

You can use the base keyword in a constructor, to call the constructor of a class’ base class.  You’d most typically do this to allow the constructor in the base class to initialize the data members that are defined in the base class.  Then the constructor of the derived class can initialize its own data members.

In the example below, the Terrier constructor uses the base keyword to invoke the Dog constructor.  Note that the Dog constructor will be executed first.

    public class Dog
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public Dog(string name, int age)
        {
            Console.WriteLine("Dog constructor");
            Name = name;
            Age = age;
        }
    }

    public class Terrier : Dog
    {
        public double GrowlFactor { get; set; }

        public Terrier(string name, int age, double growlFactor)
            : base(name, age)
        {
            Console.WriteLine("Terrier constructor");
            GrowlFactor = growlFactor;
        }
    }

768-001

Advertisements