About This eBook by Bart De Smet

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

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>:

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

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

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required