Search code examples
c#genericsenumscasting

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


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;
}

Solution

  • 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)));
    }