Object Initializers

image 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 ...

Get C# 4.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.