There are certain classes in the Framework which effectively pass on special characteristics to all types derived from them but do not possess those characteristics themselves. The CLR itself imposes no prohibition against using those classes as constraints, but generic types constrained to them would not acquire the non-inherited characteristics the way concrete types would. The creators of C# decided that because such behavior might confuse some people, and they failed to see any usefulness to it, they should prohibit such constraints rather than allow them to behave as they do in the CLR.
If, for example, one were allowed to write: void CopyArray<T>(T dest, T source, int start, int count)
; one would be able to pass dest
and source
to methods which expect an argument of type System.Array
; further, one would get compile-time validation that dest
and source
were the compatible array types, but one would not be able to access elements of the array using the []
operator.
The inability to use Array
as a constraint is mostly pretty easy to work around, since void CopyArray<T>(T[] dest, T[] source, int start, int count)
will work in almost all situation where the former method would work. It does, however, have a weakness: the former method would work in the scenario that one or both of the arguments was of type System.Array
while rejecting cases where the arguments are incompatible array types; adding an overload where both arguments were of type System.Array
would make the code accept the additional cases it should accept, but also make it erroneously accept cases it should not.
I find the decision to outlaw most of the special constraints irksome. The only one which would have zero semantic meaning would be System.Object
[since if that were legal as a constraint, anything would satisfy it]. System.ValueType
probably wouldn't be very useful, since references of type ValueType
don't really have much in common with value types, but it might plausibly have some value in cases involving Reflection. Both System.Enum
and System.Delegate
would have some real uses, but since the creators of C# didn't think of them they're outlawed for no good reason.
System.Object
is not a "special class", as this is valid:public class X : System.Object { }
, butSystem.Object
is still a "special class". – GlyptographSystem.Object
is a special special class, since all other types derive from it, whether they like it or not. – Nesta