I was writing a generic method with enum
as the Constraint, and the compiler spat a few errors that did not directly convey to me that enum
s cannot be used as generic constraints. And I learnt the following from my investigation:
This is an excerpt from the C# Language Specification. Enum
s are value types and there is no way that you can specify the System.ValueType
as a constraint, as per the specification. But if you wish to specify a non-reference type as a [primary] constraint, struct
can be used.
private void Method<t> where T : struct
That does not guarantee that our generic method will not accept other value types, besides enum
, for which we do not support our functionality.
During the course of investigation, I was extremely surprised to know that the numeric types like int
, float
, etc. in C# are struct
. It is not far from the fact that they are value types, but it was interesting to know that they are declared as:
public struct Int32 : IComparable, IFormattable, IConvertible,
IComparable<int>, IEquatable<int>
Similar thing for other numeric types. Whereas an enum
[System.Enum], though a value type, is declared as an abstract
class that derives from System.ValueTypes
unlike the int
or float
. The end result is that enum
s are value types but I wonder about the way in which they are declared.
Anyway, the question still remains unresolved - why enum
s cannot be used as constraints, and just the specification saying that enum
s cannot be used as constraints is unsatisfactory.
I am not sure if there is any other way to resolve my situation. Question open to cyber space !!!
P.S. Refer to section 25.7 through for the specification on Generic Type Constraints.