Object Initializers
You have seen how to create constructors for your class that provide a convenient way to set the initial state. However, as with method overloading, the more fields you require to be set, the more overloaded constructors you might need to provide. Although constructors support optional parameters, sometimes you want to set properties when you create the object instance.
Classes provide an object initialization syntax that enables you to assign values to any publicly accessible fields or properties as part of the constructor call. This allows a great deal of flexibility and can significantly reduce the number of overloaded constructors you need to provide.
Listing 3.14 shows code similar to what you wrote in the "Working with Properties" section, followed by code using an object initializer. The code generated by the compiler in both cases is almost the same.
Listing 3.14. Object Initializers
Contact c1 = new Contact(); c1.FirstName = "Jim"; c1.LastName = "Morrison"; c1.DateOfBirth = new DateTime(1943, 12, 8); Console.WriteLine(c1.ToString()); Contact c2 = new Contact { FirstName = "Jim", LastName = "Morrison", DateOfBirth = new DateTime(1943, 12, 8) }; Console.WriteLine(c2.ToString());
As long as there are no dependencies between fields or properties, object initializers are an easy and concise way to instantiate and initialize an object at the same time.