Where to Use

The most important characteristic of co- and contravariance for generic interface and delegate types is its definition site characteristic. In other words, as a user of such a generic type you don’t have to do anything to get more (safe) flexibility in return. We’ve already seen how a LINQ query can now be assigned to a variable of a more general IEnumerable<T> type, where it couldn’t before.

In .NET 4, generic interfaces and delegates in the BCL have been improved by adding variance modifiers where applicable. The most important types are shown here:

image

For an example of an interface that can’t have its type parameter marked with either ...

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.