C
C#6mo 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;
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));
object? newValue = Convert.ChangeType(value, typeof(MyEnum));
But this errors saying: `System.InvalidCastException: Invalid cast from 'System.Int32' to 'MyEnum'.
2 Replies
Hugh
HughOP6mo ago
aha - amazing - this looks like it's exactly what I was after. I'll give this a go. Thanks @reflectronic Yup - this is exactly what I needed. Thanks!
Want results from more Discord servers?
Add your server