#331 – Calling a Base Class Constructor Implicitly vs. Explicitly

In a derived class, you can call a constructor in the base class explicitly using the base keyword.

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

        public Terrier(string name, int age, string attitude)
            : base(name, age)
        {
            Attitude = attitude;
        }

If you don’t explicitly call a base class constructor, the default (parameterless) constructor is called implicitly.

        public Terrier(string name, int age, string attitude)
        {
            // Default Dog constructor has already been called
            //   at this point.
            Name = name;
            Age = age;
            Attitude = attitude;
        }

If you do omit the base keyword, the base class must define a default (parameterless) constructor.  If it doesn’t, the compiler will complain that the base class doesn’t have a constructor that takes 0 arguments.

Advertisements