Default Value Expression

As you’ve seen repeatedly, the introduction of generics in .NET 2.0 took away a bunch of limitations that came from the mandatory use of System.Object in generic code, resulting in weaker typing than desired. With generics, it’s possible to use type parameters and write code in a fashion as generic as possible.

However, sometimes one needs to synthesize a special “default value” for a type parameter without knowing the type of the parameter until runtime. All that matters to set the scene is that we are defining a generic type with a type parameter T. In the definition of that type, we don’t know anything about T. It could be an int, a string, a Customer, whatever. The generic type can use T anywhere as if it were a ...

Get C# 5.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.