Constraints are nice when you need some information about the generic type argument. By constraining the type you are not only limiting the set of valid type arguments but you are also giving yourself the ability to make compile-time decisions based on the common elements of that set of types.
In your specific example the generic constraint does not provide any benefit but in other circumstances they can. Consider this example:
T foo<T>()
{
return null;
}
This method cannot compile because the compiler knows (as well I should have when I wrote the method) that the generic type argument could possibly be a value type which cannot be set to null
. By adding a constraint I can make this code compile:
T foo<T>()
where T : class
{
return null;
}
I have now limited the valid set of generic type arguments to just classes. Since the compiler now knows that T
must be a class it allows me to return null
since there are no scenarios in which null
could not be returned. While this is not a terribly useful example I am sure you can extrapolate ways that this can be helpful.