Quantcast
Viewing latest article 2
Browse Latest Browse All 7

#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)
        {
            thing.Bury();
        }

        public void Eat(TFavFood eatThis)
        {
            eatThis.Eat();
        }
    }

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

Filed under: Basics Tagged: Basics, C#, Constraints, Generic, Type Parameters, Where Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing latest article 2
Browse Latest Browse All 7

Trending Articles