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

Viewed 28260

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?

3 Answers

For information, using the generic constraint Enum is available from C# 7.3 and greater.

Related