Object Initializers in .NET 3.5

One compiler improvement in .NET 3.5 is the object initializers feature that lets you concisely set properties of an object as you create it.

If you’ve ever used VB.NET you may well have found and enjoyed the with keyword to write code such as:

Dim myObj As MyClass
myObj = New MyClass()
With myObj
  .ProductCode = "ABC123"
  .Quantity = 5
  .Cost = 567.89
End With

This is more concise than writing myObj several times over, especially if setting a large number of properties, but as C# has no such keyword many people resorted to providing helpful constructors to facilitate code like:

MyClass myObj = new MyClass("ABC123", 5, 567.89);

If all three of these properties are essential then this makes for a sensible constructor however many classes have a number of properties that are optional and class designers struggle to determine whether to make constructors that merely cut-down on typing and which of the various combinations of optional properties might make sense in having their own constructor.

Invariably the combination you might want doesn’t exist and if it does the chances of being able to understand which properties are being set from one of a number of constructors that take parameters of similar types is quite low unless you go and take a peek with the IntelliSense.

Using object initializers you can stick to creating constructors that reflect parameters necessary to ensure your object is in a valid state and forget about providing helpful ones for those optional parameters. In our example if we assume the ProductCode is essential and the others are optional we can write code like:

MyClass myObj = new MyClass("ABC123") { Quantity = 5, Cost = 567.89 };

Which is both concise and easy to understand. It also requires no work on the part of the class designer and therefore works with all your existing classes. You can also nest them to set properties that require more complex types such as:

MyClass myObj = new MyClass("ABC123") {
   Quantity = 5,
   Cost = 567.89,
   Category = new Category("A") { Description = "New machine" }
};

This feature is no use if your objects are immutable in which case constructors are your only friend.

[)amien

0 responses