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 ever since the introduction of generics, 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:

image

In the preceding code, the query expression passed to MakeJuice will be inferred to be of type IEnumerable<Apple>. Based on the translation of the query ...

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.