Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing base class as generic for IEnumerable<T>
    primarykey
    data
    text
    <p>I have a good understanding of OOP in general, inheritance and polymorphism, interfaces, etc. I encountered a strange situation and I don't understand why it does not work at all...</p> <p>EDIT : Ok, I found out that covariance (or contravariance?) may solve this problem, but crucially</p> <h2>we're still using .NET 2.0 </h2> <p>How can I solve this without moving to C# 4.0 ?</p> <p>Here is the situation. Given these two classes :</p> <pre><code>public class CustomCollectionType&lt;T&gt; : IEnumerable&lt;T&gt; { /* Implementation here, not really important */ } public class Entity : EntityBase { /* Implentation here, not important */ } </code></pre> <p>The compiler complains when I try to have this generic method </p> <pre><code>public void LoopThrough(IEnumerable&lt;EntityBase&gt; entityList) { foreach(EntityBase entity in entityList) { DoSomething(entity); } } </code></pre> <p>And try to use it this way :</p> <pre><code>CustomCollectionType&lt;Entity&gt; entityList; /* Add items to list */ LoopThrough(entityList); </code></pre> <p>Error says I cannot convert from <code>CustomCollectionType&lt;Entity&gt;</code> to <code>IEnumerable&lt;EntityBase&gt;</code>.</p> <p>However, I can do this :</p> <pre><code>public void Foo(EntityBase entity) { entity.DoSomething(); } Foo(new Entity()); </code></pre> <p>And this :</p> <pre><code>public void Bar(IEnumerable&lt;Entity&gt; entityList) { ... } CustomCollectionType&lt;Entity&gt; entityList; Bar(entityList); </code></pre> <p>Why can't I create my method with the highest classes in the hierarchy? The types are obviously compatible... Am I missing something ?</p> <p>EDIT : I want to solve this problem without altering the existing classes in any way, so creating a new method in any of the classes, or implementing an additional interface is out of the question.</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.
 

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