C#C
C#4y ago
Sidia

Use derived classes as generic parameter

So I have tried doing following (wrote a testscript to make it more presentable):

public class Animal
{
    public string Name;
}

public class Dog : Animal
{
    public Color Color;
}

public class Cat : Animal
{
    public float Weight;
}

public class Food<TAnimal> where TAnimal : Animal
{
    public void Feed()
    {
        
    }
}

public class Testing
{

    public Testing()
    {
        // works
        var animals = new List<Animal>()
        {
            new Dog(),
            new Cat(),
        };
        
        // fail
        var animalFood = new List<Food<Animal>>()
        {
            new Food<Dog>(),
            new Food<Cat>()
        };
        
    }
}


Is there any way to build such a list?
Was this page helpful?