Annoyances with Generic Types

The mainstream .NET languages, C# and VB, introduced the concept of generic co- and contravariance as part of the .NET 4 release. Even though the CLR has supported those concepts since the introduction of generics in version 2.0, they never were exposed through the various languages. However, with the advent of LINQ in .NET 3.5, the need became much more apparent. Before explaining those concepts, let’s take a look at one of the little annoyances that pop up when using LINQ:

IEnumerable<Apple> apples = ...;var juice = MakeJuice(from apple in apples                      where apple.Color == Color.Red                      select apple);

In the preceding code, the query expression passed ...

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.