Possible Duplicate:
Enum type constraints in C#
Is it possible to use enum
types as a generic paramter by using its wrapper class Enum
?
I have different enums:
enum errors1 { E1, E3, E8 }; enum errors2 { E0, E2, E9 }; enum errors3 { E7, E4, E5 };
With the following class declaration I thought I could achieve it:
public class MyErrors<T> where T : Enum { T enumeration; public T getEnumeration() { return enumeration; } static void Main(string[] args) { Program<error1> p = new Program<error1>(); p.getEnumeration().E1 // this call does NOT work }
However, since the general type is Enum
I can only access the member and methods of the Enum
class. So is it possible to implement it the way I meant to or what other approach should I use?
Enum, Interfaces, and Generics Enum cannot extend a class, but can implement an interface because Java does not support multiple inheritances of classes but multiple implementation of interfaces. The enum is a default subclass of the generic Enum<T> class, where T represents generic enum type.
Extra Credit: It turns out that a generic restriction on enum is possible in at least one other .
The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.
An enum type is a special data type that enables for a variable to be a set of predefined constants.
No, it's not possible unfortunately. The best you can do is use where T : struct, IComparable, IConvertible, IFormattable
(which of course is not the same). The interface restrictions are derived from the implementation of System.Enum
.
Apart from that, you can check if typeof(T).IsEnum
, which can detect the problem at runtime and presumably throw an exception. But there is no way to enforce this restriction at compile time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With