Hooked on LINQ

Hooked on LINQ - Developers' Wiki
for .NET Language Integrated Query

Quick Search

Advanced Search »

Object Initializers

Modified: 2008/01/27 19:19 by t_magennis - Categorized as: Language
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.

Edit

References

Google search: Object Initializers C#

If you would like to comment on this page, click on the Discuss button located on the top-right of each page. Feel free to edit any mistakes or ommissions you find. If you have an objection or find in-appropriate content then contact the administrator. This website is not affiliated with Microsoft®, all content and opinions are those of the specific author and some advice, solutions and article may contain un-intentional errors - please use care. Powered by ScrewTurn Wiki version 2.0.33. Some of the icons created by FamFamFam.