O'Reilly logo

C# 4.0 Unleashed by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Generic Co- and Contravariance

Let’s take a closer look at co- and contravariance on generic interface types. At the start of this chapter, you saw how the next piece of code didn’t compile in .NET 3.5, with the assumption that MakeJuice takes in an IEnumerable<Fruit>:

image

The reason is that IEnumerable<T> was invariant in its type parameter T. Invariance simply means that no typing relationship between the types IEnumerable<Base> and IEnumerable<Derived> is established. They’re treated as unrelated to one another.

In .NET 4, IEnumerable<T> has been marked as covariant by putting the out keyword on the type parameter T:

By using the out keyword, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required