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>
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.
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.
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.
public class Animal<SpeciesType,OrderType> where SpeciesType : Species where OrderType : Order { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With