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

27,352

Solution 1

Like this:

return (T)(object)value;

Solution 2

Change this:

Enum value = (Enum)Enum.ToObject(enumType, enumAsInt);

to this:

T value = (T)Enum.ToObject(enumType, enumAsInt);

and remove the cast :)

Solution 3

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

Share:
27,352

Related videos on Youtube

Justin
Author by

Justin

I'm a developer.

Updated on May 15, 2020

Comments

  • Justin
    Justin almost 4 years

    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?

    • nawfal
      nawfal almost 11 years
      Note that if the case had been other way around, say, you have to do (Enum)value and you get Cannot convert type 'T' to 'System.Enum', you could merely do an as cast, like value as Enum.
    • keithl8041
      keithl8041 about 10 years
      Not true (at least in my case), you get the old 'The as operator must be used with a reference or nullable type ('Foo.bar' is a non-nullable value type) error.
  • João Angelo
    João Angelo almost 14 years
    It would be better to initially declare value as an object.
  • Justin
    Justin almost 14 years
    Thanks that seems to compile. I don't understand the reason for the error then? Bonus points if you can explain why in the interest of learning:)
  • SLaks
    SLaks almost 14 years
    The compiler doesn't realize that T is a enum type. As far as it is aware, T might be DateTime. Therefore, you cannot cast directly from any type other than object to T.
  • Justin
    Justin almost 14 years
    I did try to constrain T in the method signature with "where T : Enum". But the compiler tells me Constraint cannot be special class 'System.Enum'.
  • SLaks
    SLaks almost 14 years
  • AgentFire
    AgentFire about 9 years
    Can't this be done without box-unbox? May be using this __makeref thing
  • Tod Cunningham
    Tod Cunningham over 5 years
    I couldn't get Slaks solution to work, but using the Enum.ToObject cast worked great.