You can enforce a constraint on a type parameter for a generic class using the where keyword. Following the wherekeyword, you typically indicate a type or interface that the actual parameter must adhere to.
You can define more than one constraint for the same type parameter.
In the example below, the TFavThing parameter must represent a type that implements both the IBuryable andIEdible interfaces.
1
2
3
4
5
6
7
8
9
10
11
12
public
class
Dog<TFavThing>
where
TFavThing: IBuryable, IEdible
{
public
void
BuryThing(TFavThing thing)
{
thing.Bury();
}
public
void
Eat(TFavThing eatThis)
{
eatThis.Eat();
}
1
2
3
4
5
Dog<Bone> d =
new
Dog<Bone>(
"Buster"
, 5);
Bone myBone =
new
Bone(
"Rawhide"
);
d.BuryThing(myBone);
d.Eat(myBone);
1
2
3
4
5
6
7
8
9
10
11
12
| public class Dog<TFavThing> where TFavThing: IBuryable, IEdible { public void BuryThing(TFavThing thing) { thing.Bury(); } public void Eat(TFavThing eatThis) { eatThis.Eat(); } |
1
2
3
4
5
| Dog<Bone> d = new Dog<Bone>( "Buster" , 5); Bone myBone = new Bone( "Rawhide" ); d.BuryThing(myBone); d.Eat(myBone); |