O'Reilly logo

C# 5.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

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

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