BT

C# Feature Focus: Co- and Contra-variance

by Jonathan Allen on Oct 27, 2008 |

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

Hello stranger!

You need to Register an InfoQ account or to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Tell us what you think

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

More Information by Jonathan Allen

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

1 Discuss

Educational Content

General Feedback
Bugs
Advertising
Editorial
InfoQ.com and all content copyright © 2006-2013 C4Media Inc. InfoQ.com hosted at Contegix, the best ISP we've ever worked with.
Privacy policy
BT