#546 – Specifying More than One Constraint for the Same Type Parameter
March 23, 2012 Leave a comment
You can enforce a constraint on a type parameter for a generic class using the where keyword. Following the where keyword, 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 and IEdible interfaces.
public class Dog<TFavThing> where TFavThing: IBuryable, IEdible { public void BuryThing(TFavThing thing) { thing.Bury(); } public void Eat(TFavThing eatThis) { eatThis.Eat(); }
Dog<Bone> d = new Dog<Bone>("Buster", 5); Bone myBone = new Bone("Rawhide"); d.BuryThing(myBone); d.Eat(myBone);