#704 – Using an Object Initializer with Any Constructor
October 31, 2012 Leave a comment
One common pattern for using an object initializer to initalize select properties or fields of an object is to use the following syntax.
Dog d = new Dog { Name = "Bowzer", Age = 2 };
When using this syntax, the default (parameterless) constructor for the class is called. After the object is constructed, the specified values are assigned to the appropriate properties.
You can also construct the object using any custom constructor, followed by an object initializer.
For example, let’s say that the Dog class only has a single constructor, which takes two arguments to set the Name and Age properties. You can then do the following:
Dog d = new Dog("Bowzer", 2) { CollarSize = 12.4 };
The constructor is called, setting Name and Age. After the object is constructed, the CollarSize property is initialized to contain a value of 12.4.