Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Variance will only be supported in a <em>safe</em> way - in fact, using the abilities that the CLR already has. So the examples I give in the book of trying to use a <code>List&lt;Banana&gt;</code> as a <code>List&lt;Fruit&gt;</code> (or whatever it was) still won't work - but a few other scenarios will.</p> <p>Firstly, it will only be supported for interfaces and delegates.</p> <p>Secondly, it requires the author of the interface/delegate to decorate the type parameters as <code>in</code> (for contravariance) or <code>out</code> (for covariance). The most obvious example is <code>IEnumerable&lt;T&gt;</code> which only ever lets you take values "out" of it - it doesn't let you add new ones. That will become <code>IEnumerable&lt;out T&gt;</code>. That doesn't hurt type safety at all, but lets you return an <code>IEnumerable&lt;string&gt;</code> from a method declared to return <code>IEnumerable&lt;object&gt;</code> for instance.</p> <p>Contravariance is harder to give concrete examples for using interfaces, but it's easy with a delegate. Consider <code>Action&lt;T&gt;</code> - that just represents a method which takes a <code>T</code> parameter. It would be nice to be able to convert seamlessly use an <code>Action&lt;object&gt;</code> as an <code>Action&lt;string&gt;</code> - any method which takes an <code>object</code> parameter is going to be fine when it's presented with a <code>string</code> instead. Of course, C# 2 already has covariance and contravariance of delegates to some extent, but via an actual conversion from one delegate type to another (creating a new instance) - see P141-144 for examples. C# 4 will make this more generic, and (I believe) will avoid creating a new instance for the conversion. (It'll be a reference conversion instead.)</p> <p>Hope this clears it up a bit - please let me know if it doesn't make sense!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload