C# Feature Focus: Co- and Contra-variance
In order to match Java and support J#, .NET arrays have always been co-variant. Unfortunately it was done so in an unsafe fashion, necessitating the need for runtime checks whenever storing values in an array. For .NET 2 and generics, neither co- nor contra-variance was supported.
.NET 4 will support safe co- and contra-variance on interfaces and delgates. In order to do this types in the interface can be marked with either an "in" or "out" modifier. If marked as out, the interface supports co-variance and the given type can only appear as a return type or read-only property. If marked in, the type can only appear as a parameter or set-only property.
This support is only for reference types, no variance is allowed on structures. Also, parameters passed by reference are not allowed. IEnumerable, IQueryable, Func, and Action are examples of primary interfaces and delegates that will be marked for variance support.
For more information on this see our article Covariance and Contravariance in .NET Generics and Eric Lippert's Co- and contra-variance: how do I convert a List(Of Apple) into a List(Of Fruit).
Roy Rapoport Aug 28, 2014