Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> 
like image 435
Luke Avatar asked Sep 05 '08 17:09

Luke


People also ask

Can a generic class have multiple constraints?

There can be more than one constraint associated with a type parameter. When this is the case, use a comma-separated list of constraints. In this list, the first constraint must be class or struct or the base class.

What keyword allows you to put constraints on a generic type?

So here is the list of some of the constraints that you can add to the generic classes, using the where keyword: Restrict the generic class to use the type parameter of value or reference type only (as we discussed above). Restrict the type parameter T, to be implementing the specified interface.

Can generic classes be constrained?

Declaring those constraints means you can use the operations and method calls of the constraining type. If your generic class or method uses any operation on the generic members beyond simple assignment or calling any methods not supported by System. Object, you'll apply constraints to the type parameter.


1 Answers

public class Animal<SpeciesType,OrderType>     where SpeciesType : Species     where OrderType : Order { } 
like image 138
Darren Kopp Avatar answered Sep 19 '22 00:09

Darren Kopp