#289 – You Can Define Multiple Constructors
April 2, 2011 1 Comment
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
Pingback: #693 – Named Arguments in Constructors Allow the Most Flexibility « 2,000 Things You Should Know About C#