Where and When to Use Variance

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:

// Used on collections and in LINQ.interface IEnumerable<out T>;interface IEnumerator<out T>;interface IQueryable<out T>;// Interfaces ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.