#692 – Two Approaches for Optional Parameters in Constructors
October 15, 2012 Leave a comment
When you create an instance of an object, you may want to pass different combinations of parameters for purposes of initializing the object. In authoring a class, there are a couple different ways to support this.
You can declare multiple constructors, each supporting a different set of parameters. You can use constructor chaining to invoke the main constructor, to centralize object initialization.
public Dog(string name, int age, string favToy ) { // Do all parameter validation here Name = name; Age = age; FavoriteToy = favToy; } public Dog(string name) : this(name, 1, null) { } public Dog(string name, int age) : this(name, age, null) { } public Dog(string name, string favToy) : this(name, 1, favToy) { }
You can also use optional parameters in a single constructor, to do the same thing.
public Dog(string name, int age = 1, string favToy = null) { // Do all parameter validation here Name = name; Age = age; FavoriteToy = favToy; }