#546 – Specifying More than One Constraint for the Same Type Parameter

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);
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: