Object initializers allow you to create an object and initialize its public
properties (and public
instance variables, if any) in the same statement. This can be useful when a class does not provide an appropriate constructor to meet your needs, but does provide a constructor that can be called with no arguments and properties that you can use to set the class’s data. The following statements demonstrate object initializers using the class Time2
from Fig. 10.5.
// create a Time2 object and initialize its properties
var aTime = new Time2 {Hour = 14, Minute = 30, Second = 12};
// create a Time2 object and initialize only its Minute property
var anotherTime = new Time2 {Minute = 45};
The first statement creates a Time2
object (aTime
), initializes it with class Time2
’s constructor that can be called with no arguments, then uses an object initializer to set its Hour
, Minute
and Second
properties. Notice that new
Time2
is immediately followed by an object-initializer list—a comma-separated list in curly braces ({
}
) of properties and their values. Each property name can appear only once in the object-initializer list. The object initializer executes the property initializers in the order in which they appear.
The second statement creates a new Time2
object (anotherTime
), initializes it with class Time2
’s constructor that can be called with no arguments, then sets only its Minute
property using an object initializer. When the Time2
constructor is called with no arguments, it initializes the time to midnight. The object initializer then sets each specified property to the supplied value. In this case, the Minute
property is set to 45
. The Hour
and Second
properties retain their default values, because no values are specified for them in the object initializer.