Home > OS >  cast integer to generic enum types that have a different underlying type
cast integer to generic enum types that have a different underlying type

Time:09-30

The function below only works when the parameter type is the same as the underlying type of T. How can I make it work for all enum? (I don't care about narrowing or widening)

public T Cast<T>(int i) where T : Enum
{
  return (T)(object)i;
}

CodePudding user response:

You can do that for example like this:

public static T Cast<T>(int i) where T : Enum {
    return (T)Convert.ChangeType(i, Enum.GetUnderlyingType(typeof(T)));
}
  • Related