#1,037 – Specifying Type Parameter Constraints for More than One Type Parameter

If you define a generic type that includes more than one type parameter, you can specify type parameter constraints for each parameter independently.

In the example below, we define a generic class that accepts two type parameters.  We specify that the first type must be one that implements the IMoo interface and that the second type must implement IBark.

    public class MooBarkPile<T1,T2> where T1 : IMoo
                                   where T2 : IBark
    {
        private List<T1> mooPile = new List<T1>();
        private List<T2> barkPile = new List<T2>();

        public void AddMooThing(T1 thing)
        {
            mooPile.Add(thing);
            mooPile[mooPile.Count - 1].Moo();
        }

        public void AddBarkThing(T2 thing)
        {
            barkPile.Add(thing);
            barkPile[barkPile.Count - 1].Bark("Woof");
        }
    }

We can now use the type as follows:

            MooBarkPile<Cow,Dog> aPile = new MooBarkPile<Cow,Dog>();
            aPile.AddBarkThing(new Dog("Kirby", 10));
            aPile.AddMooThing(new Cow("Bessie"));

1037-001

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.

2 Responses to #1,037 – Specifying Type Parameter Constraints for More than One Type Parameter

  1. Pingback: Dew Drop – February 20, 2014 (#1727) | Morning Dew

  2. Pingback: Dark Core | //Build March 4, 2014

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: