#590 – Optional Parameters in Constructors
May 24, 2012 Leave a comment
You’ll typically see optional parameters in methods. But you can also define an optional parameter in a constructor:
public string Name { get; set; } public int Age { get; set; } public string FavoriteToy { get; set; } public Dog Father { get; set; } public Dog Mother { get; set; } public Dog(string name, int age = 1, string favToy = "Bone", Dog father = null, Dog mother = null) { Name = name; Age = age; FavoriteToy = favToy; Father = father; Mother = mother; }
Dog kirby = new Dog("Kirby", 15, "Ball"); Dog sonOfKirby = new Dog("Ferbie", 2, "Frisbee", kirby);
Optional parameters in constructors avoid the need to chain constructors.