#545 – Specifying Constraints for More than One Type Parameter

When specifying constraints for type parameters in a generic class, you can specify constraints for more than one parameter.

To specify more than one constraint, just place each constraint on a separate line, with its own where clause.

    // TFavThing type parameter must be a type that implements IBuryable
    // TFavFood type parameter must be a type that implements IEdible
    public class Dog<TFavThing,TFavFood>
        where TFavThing: IBuryable
        where TFavFood: IEdible
        public void BuryThing(TFavThing thing)

        public void Eat(TFavFood eatThis)

When constructing this type, we just need to use types that implement the specified interfaces.

            // Bone implements IBuryable
            // RawFood implements IEdible
            Dog<Bone,RawFood> d = new Dog<Bone,RawFood>("Buster", 5);

            d.BuryThing(new Bone("Rawhide"));
            d.Eat(new RawFood(16));  // 16 oz chunk

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: