Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

Where enum does not work !!!

, 30 Jul 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

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 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)

Share

About the Author

Vivek Ragunathan
Software Developer (Senior)
United States United States
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141223.1 | Last Updated 30 Jul 2010
Article Copyright 2010 by Vivek Ragunathan
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid