C#C
C#2y ago
Hugh

✅ Casting to enum when only having a Type object

Does anyone know how it's possible to cast while only having a Type object, and not the actual type at compile time?

I've got an enum (MyEnum), and an integer value (value)

I want to do the equivalent of this:
object? newValue = (MyEnum)value;


While only having access to typeof(MyEnum) and not knowing what MyEnum actually is.

I had thought I could do this:

object? newValue = Convert.ChangeType(value, typeof(MyEnum));


But this errors saying: `System.InvalidCastException: Invalid cast from 'System.Int32' to 'MyEnum'.
Was this page helpful?