© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
4 replies
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?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ Class with parameter as a generic parameter
C#CC# / help
4y ago
❔ [Unity?] How to have a list of generic classes in inspector cast as derived class
C#CC# / help
3y ago
❔ How do generic parameters with static classes work?
C#CC# / help
4y ago
❔ You cannot use a covariant type parameter as a generic type constraint for interface methods.
C#CC# / help
3y ago