Luke
Luke

Reputation: 18993

How do I specify multiple constraints on a generic type in C#?

What is the syntax for placing constraints on multiple types? The basic example:

class Animal<SpeciesType> where SpeciesType : Species

I would like to place constraints on both types in the following definition such that SpeciesType must inherit from Species and OrderType must inherit from Order:

class Animal<SpeciesType, OrderType>

Upvotes: 33

Views: 9796

Answers (2)

Ryan Lanciaux
Ryan Lanciaux

Reputation: 5976

You should be able to go :

class Animal<SpeciesType, OrderType>
    where SpeciesType : Species
    where OrderType : Order {
}

Upvotes: 18

Darren Kopp
Darren Kopp

Reputation: 77697

public class Animal<SpeciesType,OrderType>
    where SpeciesType : Species
    where OrderType : Order
{
}

Upvotes: 60

Related Questions