BT

New Early adopter or innovator? InfoQ has been working on some new features for you. Learn more

C# Feature Focus: Co- and Contra-variance

| by Jonathan Allen Follow 34 Followers on Oct 27, 2008. Estimated reading time: less than one minute |

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

Rate this Article

Adoption Stage
Style

Hello stranger!

You need to Register an InfoQ account or or login 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

Login to InfoQ to interact with what matters most to you.


Recover your password...

Follow

Follow your favorite topics and editors

Quick overview of most important highlights in the industry and on the site.

Like

More signal, less noise

Build your own feed by choosing topics you want to read about and editors you want to hear from.

Notifications

Stay up-to-date

Set up your notifications and don't miss out on content that matters to you

BT