Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Both covariance and contravariance in C# 4.0 refer to the ability of using a derived class instead of base class. The in/out keywords are compiler hints to indicate whether or not the type parameters will be used for input and output.</p> <h3>Covariance</h3> <p>Covariance in C# 4.0 is aided by <code>out</code> keyword and it means that a generic type using a derived class of the <code>out</code> type parameter is OK. Hence</p> <pre><code>IEnumerable&lt;Fruit&gt; fruit = new List&lt;Apple&gt;(); </code></pre> <p>Since <code>Apple</code> is a <code>Fruit</code>, <code>List&lt;Apple&gt;</code> can be safely used as <code>IEnumerable&lt;Fruit&gt;</code></p> <h3>Contravariance</h3> <p>Contravariance is the <code>in</code> keyword and it denotes input types, usually in delegates. The principle is the same, it means that the delegate can accept more derived class.</p> <pre><code>public delegate void Func&lt;in T&gt;(T param); </code></pre> <p>This means that if we have a <code>Func&lt;Fruit&gt;</code>, it can be converted to <code>Func&lt;Apple&gt;</code>.</p> <pre><code>Func&lt;Fruit&gt; fruitFunc = (fruit)=&gt;{}; Func&lt;Apple&gt; appleFunc = fruitFunc; </code></pre> <h3>Why are they called co/contravariance if they are basically the same thing?</h3> <p>Because even though the principle is the same, safe casting from derived to base, when used on the input types, we can safely cast a less derived type (<code>Func&lt;Fruit&gt;</code>) to a more derived type (<code>Func&lt;Apple&gt;</code>), which makes sense, since any function that takes <code>Fruit</code>, can also take <code>Apple</code>.</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