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

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

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

Facebook photo

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

Connecting to %s

%d bloggers like this: