How to cast a variable of an enum generic type to int and back

Viewed 153

I am using C# to write a class that takes an enum type parameter, like this:

class EnumWrapper<T>
    where T: Enum
{
}

Inside the class, I have a method that takes an argument of type T, and I need to cast it to an int, like this:

void DoSomething(T arg)
{
    int a = (int)arg;
}

But the compiler issues a CS0030 error "Cannot convert type 'T' to 'int'. Something similar happens when I try to cast an int back into a T. However, this works with a fixed enum type that is not provided via a type parameter. For example, this works fine:

void DoSomething(DayOfWeek arg)
{
    int a = (int)arg;
}

Why is this happening, and how can I cast between a generic enum type and int?

1 Answers

You may add IConvertible to generic constraint and use ToInt32 method, something like

class EnumWrapper<T>
    where T : Enum, IConvertible
{
    void DoSomething(T arg)
    {
        int a = arg.ToInt32(null);
    }
}

Have a look at the Enum constraint for details. Also, as mentioned in comments, it isn't necessary that your enum is based on int type

Related