#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>();

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

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

  1. Very clear and easy to understand thanks

Leave a comment