#1,030 – Requiring Generic Type Parameters to Derive from a Specified Class

By default, when you specify a type parameter in a generic class, the type can be any .NET type.  There are times, however, when you’d like to constrain the type in some ways, allowing only certain types.

You can constrain a type parameter to be of a type that derives from (or is identical to) a particular type, using the where keyword.  In the example below, the PileOf class has a type parameter that must derive from Animal–because we look for a Habitat property.

    public class PileOf<T> where T : Animal
    {
        private List<T> thePile;
        private List<string> habitats;

        public PileOf()
        {
            thePile = new List<T>();
            habitats = new List<string>();
        }

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

We can construct a PileOf<Dog>, but not a PileOf<int>.

            // Works
            PileOf<Dog> dogPile = new PileOf<Dog>();
            dogPile.AddThing(new Dog("Fido"));

            // Compile-time error: int can't be converted to Animal
            PileOf<int> intPile = new PileOf<int>();