A constraint on a type parameter is often a base class or interface, but can actually take on a number of different forms.
A constraint can be a class type:
1
2
3
4
| // Type parameter can be some subclass of DogToy, // e.g. SqueakyToy, RopeToy public class Dog where TFavThing: DogToy |
Or an interface type:
1
2
| public class Dog where TFavThing: IBuryable |
Or another type parameter:
1
2
3
4
5
| // TFavThing must implement IBuryable // TOtherThing must be castable to TFavThing's type public class Dog<TFavThing,TOtherThing> where TFavThing: IBuryable where TOtherThing: TFavThing |
class indicates that the type must be a reference type.
1
2
| public class Dog<TFavThing> where TFavThing: class |
struct indicates that the type must be a non-nullable value type.
1
2
| public class Dog<TFavThing> where TFavThing: struct |
new() indicates that the type must have a public parameterless constructor defined.
1
2
| public class Dog<TFavThing> where TFavThing: new () |