Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>Can someone explain the usage of the out T part with an example?</p> </blockquote> <p>Sure. <code>IEnumerable&lt;T&gt;</code> is covariant. That means you can do this:</p> <pre><code>static void FeedAll(IEnumerable&lt;Animal&gt; animals) { foreach(Animal animal in animals) animal.Feed(); } ... IEnumerable&lt;Giraffe&gt; giraffes = GetABunchOfGiraffes(); FeedAll(giraffes); </code></pre> <p>"Covariant" means that <em>the assignment compatibility relationship of the type argument is preserved in the generic type</em>. <code>Giraffe</code> is assignment compatible with <code>Animal</code>, and therefore that relationship is preserved in the constructed types: <code>IEnumerable&lt;Giraffe&gt;</code> is assignment compatible with <code>IEnumerable&lt;Animal&gt;</code>.</p> <blockquote> <p>Why is applicable only for interfaces and delegates and not for classes?</p> </blockquote> <p>The problem with classes is that classes tend to have mutable fields. Let's take an example. Suppose we allowed this:</p> <pre><code>class C&lt;out T&gt; { private T t; </code></pre> <p>OK, now think this question through carefully before you go on. <strong>Can <code>C&lt;T&gt;</code> have any method outside of the constructor that sets the field <code>t</code> to something other than its default?</strong></p> <p>Because it must be typesafe, <code>C&lt;T&gt;</code> can now have no methods that take a T as an argument; T can only be returned. So who sets t, and <em>where do they get the value they set it from</em>?</p> <p>Covariant class types really only work if the class is <em>immutable</em>. And we don't have a good way to make immutable classes in C#.</p> <p>I wish we did, but we have to live with the CLR type system that we were given. I hope in the future we can have better support for both immutable classes, and for covariant classes.</p> <p>If this feature interests you, consider reading my long series on how we designed and implemented the feature. Start from the bottom:</p> <p><a href="https://blogs.msdn.microsoft.com/ericlippert/tag/covariance-and-contravariance/" rel="noreferrer">https://blogs.msdn.microsoft.com/ericlippert/tag/covariance-and-contravariance/</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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