Sidia
Sidia
CC#
Created by Sidia on 10/25/2022 in #help
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?
5 replies