Object Initializers

Calling constructors is an essential mechanism for creating new instances of objects, but sometimes it doesn’t suffice. A common problem with constructors is the number of overloads they have to accommodate for various scenarios. For example, the TimeSpan type has no fewer than four constructor overloads for developer convenience. Internally, a TimeSpan simply consists of a tick count, but as you’ve seen, more handy overloads exist that allow us to supply hours, minutes, and seconds (for example).

It turns out TimeSpan is a type that leads to a good developer experience: The most useful overloads are available, so while browsing the list of overloads, you’ll most certainly want something that’s close enough to what you want. ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.