Note that there are some explanatory texts on larger screens.

plurals
  1. POC# Generics Inheritance Problem
    primarykey
    data
    text
    <p>I'd like to add different types of objects derived from one class with generics into a List of base type. I get this compile error</p> <pre><code>Error 2 Argument 1: cannot convert from 'ConsoleApplication1.Stable' to 'ConsoleApplication1.ShelterBase&lt;ConsoleApplication1.AnimalBase&gt;' C:\Users\ysn\Desktop\ConsoleApplication1\ConsoleApplication1\Program.cs 43 26 ConsoleApplication1 </code></pre> <p>I can't see the problem could you provide me an alternative way of doing this kind of thing?</p> <pre><code>abstract class AnimalBase { public int SomeCommonProperty;} abstract class ShelterBase&lt;T&gt; where T : AnimalBase { public abstract List&lt;T&gt; GetAnimals(); public abstract void FeedAnimals(List&lt;T&gt; animals); } class Horse : AnimalBase { } class Stable : ShelterBase&lt;Horse&gt; { public override List&lt;Horse&gt; GetAnimals() { return new List&lt;Horse&gt;(); } public override void FeedAnimals(List&lt;Horse&gt; animals) { // feed them } } class Duck : AnimalBase { } class HenHouse : ShelterBase&lt;Duck&gt; { public override List&lt;Duck&gt; GetAnimals() { return new List&lt;Duck&gt;(); } public override void FeedAnimals(List&lt;Duck&gt; animals) { // feed them } } class Program { static void Main(string[] args) { List&lt;ShelterBase&lt;AnimalBase&gt;&gt; shelters = new List&lt;ShelterBase&lt;AnimalBase&gt;&gt;(); ///////////////////////////// following two lines do not compile shelters.Add(new Stable()); shelters.Add(new HenHouse()); ///////////////////////////// foreach (var shelter in shelters) { var animals = shelter.GetAnimals(); // do sth with 'animals' collection } } } </code></pre>
    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.
 

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