Generic Type Constraints: Where Keyword in C#

In my previous article we discussed the concept of generic classes. It was based on creating a blueprint of the class, to use with any type and then using its functionality without restriction of data type, that can be used with it. Proceeding on the same lines, we will discuss the where keyword in C#, that can be used in combination with the generic classes to add some constraints on it. By adding the constraints, your generic class can only be instantiated with the conditions specified using this where keyword. It is also referred to as a constraint on the generic types and we will see why that is so.

So, we have a generic class with generic parameter type T and we apply the constraint on it with the type parameter T, that is being used with the generic class that must be of value type, since we have restricted the use of this class with a struct type only, by adding the where keyword. See the code below:

So the code above compiles and works fine. However, if you try to instantiate the generic class with the reference type, you will get a compile time error, since we added the constraint that the T type must be a value type. Similarly, you can restrict it to be used only for the reference type by specifying the class keyword, instead of the struct keyword. So here is the list of some of the constraints that you can add to the generic classes, using the where keyword:

  1. Restrict the generic class to use the type parameter of value or reference type only (as we discussed above).
  2. Restrict the type parameter T, to be implementing the specified interface.

    Here, the Type parameter, in other words ClassA, must be implementing the interface IConstraint (since the constraint is added by the where keyword). If any other class is used with the generic class parameter, then it will again result in a compile time error.

  3. The generic type parameter must be derived from a class, whose name is specified by the where clause in the definition of the the generic class, or it could be the class itself. See the code below:

So here, we can have the type parameter T to be of type ClassA or ClassB, but not ClassC. This is because the where keyword specifies that the type parameter should be either ClassA or any derived class from ClassA, in other words ClassB is also valid. But not ClassC, since it is independent.

Apart from these, there are a few other constraints that can be added to the generic class type. You can refer to the complete list on the MSDN here:

Happy Coding...!!