#289 – You Can Define Multiple Constructors

We can define multiple constructors in a class,  each one taking a different set of parameters.

Here’s an example where we define four different constructors for a Dog object.

        public string Name { get; set; }
        public int Age { get; set; }
        public string Motto { get; set; }

        public Dog(string name)
        {
            Name = name;
            Age = 1;
            Motto = "Happy";
        }

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

        public Dog(string name, string motto)
        {
            Name = name;
            Motto = motto;
            Age = 1;
        }

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

We now have four different ways to construct a Dog object.

            Dog d1 = new Dog("Kirby");                        // name
            Dog d2 = new Dog("Jack", 16);                     // name, age
            Dog d3 = new Dog("Ruby", "Look out window");      // name, motto
            Dog d4 = new Dog("Lassie", 71, "Rescue people");  // name, age, motto
Advertisements

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

One Response to #289 – You Can Define Multiple Constructors

  1. Pingback: #693 – Named Arguments in Constructors Allow the Most Flexibility « 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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: