Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I cast from a generic type to an enum in C#?

I'm writing an utility function that gets a integer from the database and returns a typed enum to the application.

Here is what I tried to do (note I pass in a data reader and column name instead of the int in my real function):

public static T GetEnum<T>(int enumAsInt) {     Type enumType = typeof(T);      Enum value = (Enum)Enum.ToObject(enumType, enumAsInt);     if (Enum.IsDefined(enumType, value) == false)     {         throw new NotSupportedException("Unable to convert value from database to the type: " + enumType.ToString());     }      return (T)value; } 

But it won't let me cast (T)value saying:

Cannot convert type 'System.Enum' to 'T'.

Also I've read quite a bit of mixed reviews about using Enum.IsDefined. Performance wise it sounds very poor. How else can I guarantee a valid value?

like image 583
Justin Avatar asked Jul 15 '10 23:07

Justin


People also ask

How do I cast to enum?

Use the Enum. ToObject() method to convert integers to enum members, as shown below.

Can enums be generic?

However, it is possible to use enums in generics. The MSDN article for Enum gives the following type definition for the class Enum . This definition can be used to get enum s working as generic types by constraining the generic type to those of Enum .

Can enum be generic in C#?

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


1 Answers

Like this:

return (T)(object)value; 
like image 129
SLaks Avatar answered Sep 20 '22 16:09

SLaks