Recently i added an article on the use of generic classes. It was based on creating a blue print of the class, to use with any type and then using its functionality without restriction of data type, which can be used with it. Moving on the same lines, let’s talk about one of the keywords in C#. Its the where keyword, which 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, that are specified by using the where keyword. It is also referred to as constraint on the generic types, and we will see why it is so.
So, we are having a generic class with generic parameter type T, and we apply the constraint on it that the type parameter T, which is being used with the generic class, must be of value type. See the code below :
So the above code compiles and works fine. However, if you try to instantiate the generic class with the reference type, you will get a compile time error, as 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, in place of the struct keyword. So here is the list of some of the constraints that you can add to the generic classes :
1. Restrict the generic class to use the type parameter of value or reference type only (that we discussed above).
Here, the Type parameter, i.e. ClassA must be implementing the interface IConstraint (as 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 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 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, i.e. ClassB is also valid. But not ClassC, as it is independent.
Apart from these, there are few other constraints that can be added to the generic class type. You can refer to the complete list on the MSDN here : http://msdn.microsoft.com/en-us/library/d5x73970(v=vs.100).aspx.