#619 – Calling the Constructor in a Base Class

Because a derived class does not inherit any of the constructors of the base class, it must do all of the initialization that the base class normally does.  It normally does this by using the base keyword to call the constructor of the base class.

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

        public Dog(string name)
        {
            Console.WriteLine("In Dog constructor");
            Name = name;
        }
    }

    public class Terrier : Dog
    {
        public string Temperament { get; set; }

        public Terrier(string name, string temperament) : base(name)
        {
            Console.WriteLine("In Terrier constructor");
            Temperament = temperament;
        }
    }

In the example above, the sequence when creating a Terrier object is:

  • Client code passes in name and temperament
  • Terrier constructor invokes the Dog constructor using the base keyword and passing the name parameter
  • Dog constructor does its initialization
  • Terrier constructor does its initialization

 

Advertisement