#290 – Chaining Constructors

You can have one constructor in a class call another.  This is known as constructor chaining.

With constructor chaining, one constructor calls another to help it initialize the data in the class.

As an example, assume that we have a Dog class with two constructors, one which accepts name and age parameters, and one which accepts only a name parameter.

In the example below, the constructor that takes two arguments initializes both name and age properties.  The constructor that takes only a name parameter chains to the first constructor, passing it the name parameter and a default value for age.  This first constructor is called using the this keyword.

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

        public Dog(string name, int age)
        {
            Name = name;
            Age = age;
        }

        public Dog(string name)
            : this(name, 1)
        {
        }
    }