New features in .Net 3.5 – Object Initializers

A new feature in the 3.5 framework is object initializers, object initializers allow you to set the values of public properties on an object in the constructor call. In the past you would have to create the instance of the object then assign each property one by one, for example:

_DataContext = new RdmDataContext();
_DataContext.LoadOptions = options;
_DataContext.DeferredLoadingEnabled = true;

Using the new syntax you can set the properties in a single statement:

_DataContext = new RdmDataContext() { LoadOptions = options, DeferredLoadingEnabled = true };

Much cleaner! Note that you can only set the values of public properties on the object.

Disclaimer: This post is based on Orcas CTP June 2007


Kick It on DotNetKicks.com