#544 – Specifying a Constraint for a Type Parameter

When you provide a type parameter to a generic class, you can only invoke methods in System.Object for objects of that type.

    public class Dog<TFavThing>
        public void BuryThing(TFavThing thing)
            // Err: TFavThing does not contain a definition for Bury

You can allow calling methods in a specific type by adding a constraint to the type parameter, indicating what type the parameter must conform to.  Adding a constraint lets you do two things:

  • Ensure that a type parameter belongs to a specific type
  • Allow you to call methods in a specific type, for objects whose type matches the type parameter

A constraint consists of a type parameter name following by an indication of the type that it must be.  (Generally a base class or an interface).

    // TFavThing type parameter must be a type that implements IBuryable
    public class Dog<TFavThing> where TFavThing: IBuryable