#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

 

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #619 – Calling the Constructor in a Base Class

  1. Pingback: #768 – When to Call the Constructor of a Base Class « 2,000 Things You Should Know About C#

  2. Pingback: When to Call the Constructor of a Base Class. | Sriramjithendra

Leave a comment