Generics - Constraints


In the preceding examples the type parameter was unconstrained and could be any type. On occasions, it is useful to constrain the parameter to deriving from a particular class or interface (or possibly a number of interfaces). When a type parameter is constrained, the methods of the class or interface may be used in the generic class. The syntax of specifying a constraint is as follows:

class class-name<type-parameter> where type-parameter : constraints
{
 ...
}

where constraints is a comma separated list of constraints.

There are five types of constraints:

  1. an interface constraint, where one or more interfaces are required to be implemented,
  2. a base class constraint, where a base class is required to be present in a type argument.
  3. a constructor constraint, where a parameterless constructor is required to be present (using new()),
  4. a reference type constraint, where a type argument must be a reference type (uses class),
  5. a value type constraint, where a type argument must be a value type (uses struct).

For the syntax of creating a type with multiple constraints, see the topic titled Multiple Constraints.