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?
Use the Enum. ToObject() method to convert integers to enum members, as shown below.
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 .
Extra Credit: It turns out that a generic restriction on enum is possible in at least one other .
Like this:
return (T)(object)value;
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