#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)
        {
        }
    }

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 Responses to #290 – Chaining Constructors

  1. Pingback: #644 – Chaining struct Constructors « 2,000 Things You Should Know About C#

  2. Pingback: #694 – Sequence of Events for Chained Constructors « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: