Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using enum as generic type parameter in C# [duplicate]

Tags:

c#

enums

generics

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?

like image 915
Konrad Reiche Avatar asked Jun 22 '11 10:06

Konrad Reiche


People also ask

Can enum be generic?

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.

Can enum be generic in C#?

Extra Credit: It turns out that a generic restriction on enum is possible in at least one other .

Which datatype can be used with enum?

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.

Can enum be a type?

An enum type is a special data type that enables for a variable to be a set of predefined constants.


1 Answers

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.

like image 129
Jon Avatar answered Sep 19 '22 21:09

Jon