3.5. Variance

Variance has changed in .NET 4.0. At the 2008 PDC, Anders Hejlsberg (lead architect of C#) summarized the changes to variance as "[allowing] you to do things in your code that previously you were surprised you couldn't do."

For those who are already comfortable with the concept of variance (stop looking so smug), here is the short version of what has changed in .NET 4.0:

  • You can now mark parameters in generic interfaces and delegates with the out keyword to make them covariant, and with the in keyword to make them contravariant (In and Out in VB.NET).

  • The in/out keywords have been added to some commonly used generic interface and delegate types to now enable them to support safe co- and contravariance (e.g., IEnumerable<out t>

Get Introducing .NET 4.0: with Visual Studio 2010 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.