Note that there are some explanatory texts on larger screens.

plurals
  1. POArray co-variance in C# generic list
    primarykey
    data
    text
    <p>I have an example where I want an abstract class interface to return something like this</p> <pre><code>abstract class AnimalProcessor { public abstract IList&lt;Animal&gt; ProcessResults(); } </code></pre> <p>Then the concrete examples</p> <pre><code>class GiraffeProcessor : AnimalProcessor { public override IList&lt;Animal&gt; ProcessResults() { return new List&lt;Giraffe&gt;(); } } class LionProcessor : AnimalProcessor { public override IList&lt;Animal&gt; ProcessResults() { return new List&lt;Lion&gt;(); } } </code></pre> <p>The problem is that the concrete classes need to have the same signature to override the <code>ProcessResults()</code> method so they need to return an <code>IList&lt;Animal&gt;</code>, however the ACTUAL data I want to return is an <code>IList&lt;Lion&gt;</code>, <code>IList&lt;Giraffe&gt;</code> etc, but then the calling code has to do</p> <pre><code>GiraffeProcessor processor = new GiraffeProcessor(); IList&lt;Animal&gt; results = processor.GetResults(); </code></pre> <p>Which does not give me an Ilist which is what I want.</p> <p>Problems</p> <p>1) Above code does not compile. The giraffeProcessor has to return a concrete <code>List&lt;Animal&gt;</code>, you can populate it with <code>Giraffe</code> objects but the object type you construct to return has to be <code>List&lt;Animal&gt;</code>. Not ideal.</p> <p>2) When you return the results, you can only get an <code>IList&lt;Animal&gt;</code>, not <code>IList&lt;Giraffe&gt;</code>. I have tried casting explicitly to <code>IList&lt;Giraffe&gt;</code> with <code>IList&lt;Giraffe&gt; results = (IList&lt;Giraffe&gt;) processor.GetResults();</code> which gives a runtime error, presumably because the object returned is NOT an <code>IList&lt;Giraffe&gt;</code>, it is an <code>IList&lt;Animal&gt;</code> which CONTAINS <code>Giraffe</code> objects.</p> <p>Can anyone suggest what I am doing wrong here with my design as Im a bit stumped as to the best way to accomplish this.</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