C
C#•3y 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>()
};

}
}
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?
2 Replies
Thinker
Thinker•3y ago
(and you can only specify variance on generic interfaces)
Sidia
SidiaOP•3y ago
So using animal as an interface could work? mhh damn doesnt solve my problem then :/ But thanks for your help 🙂 seems like what I wanted to do just isnt possible, gonna think of a way around it i guess

Did you find this page helpful?