#1,034 – Making One Type Parameter Depend on Another

When specifying a constraint for a type parameter, used in either a class or a method, you can constrain the type parameter to depend on another type parameter.  That is–the second type parameter must be identical to, or derive from, the first.

Below, the type argument used when calling the Subset method (U) must be identical to or derive from the type parameter used for the class (T).  This allows us to do a cast operation.

    public class PileOf<T>
    {
        private List<T> thePile = new List<T>();

        public void Add(T thing)
        {
            thePile.Add(thing);
        }

        public List<U> Subset<U>() where U : T
        {
            List<U> subset = new List<U>();
            foreach (T next in thePile)
            {
                if (next is U)
                    subset.Add((U)next);
            }

            return subset;
        }
    }

We could use this class as follows:

            PileOf<Animal> animals = new PileOf<Animal>();
            animals.Add(new Dog("Bowser", "Woof"));
            animals.Add(new Cat("Fluffy"));
            animals.Add(new Dog("Kirby", "Growf"));

            List<Dog> theDogs = animals.Subset<Dog>();
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.

One Response to #1,034 – Making One Type Parameter Depend on Another

  1. Very clear and easy to understand thanks

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: