Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / enum

Where Enum Does Not Work !!!

5.00/5 (1 vote)
30 Jul 2010CPOL1 min read 8.3K  
Where enum does not work !!!

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 enums cannot be used as generic constraints. And I learnt the following from my investigation:

This is an excerpt from the C# Language Specification. Enums 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.

C#
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:

C#
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 enums are value types but I wonder about the way in which they are declared.

Anyway, the question still remains unresolved - why enums cannot be used as constraints, and just the specification saying that enums 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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)