Back to C# Language Enhancements.Object Initializers allow us to construct, and assign property values to the new instance object in one statement. Whilst it seems like a handy syntax enhancement, it become essential when we need to construct query results in a select projection which we will see shortly.
Contact contact = new Contact();
contact.LastName = “Magennis”;
contact.DateOfBirth = new DateTime(1973,12,09);
To:
Contact contact = new Contact {
LastName = “Magennis”,
DateOfBirth = new DateTime(1973,12,09)
};
While it is generally good programming practice to use constructor arguments to ensure that a new type is stable and ready for use immediately after construction, Object initializers reduce the need to have a specific constructor for every variation of argument variation we need over time.
Although it seems to be a trivial improvement in syntax in the general form, it is essential when you begin to write select projection queries which transform and create a new object for the results of a query. We can also create a type on the fly, with a compiler generated name we don’t know at design-time forcing us to declare instance variables of this type using the
var keyword.EditReferences
Google search: Object Initializers C#