✅ 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:
While only having access to typeof(MyEnum)
and not knowing what MyEnum
actually is.
I had thought I could do this:
But this errors saying: `System.InvalidCastException: Invalid cast from 'System.Int32' to 'MyEnum'.2 Replies
Enum.ToObject Method (System)
Converts a specified integer value to an enumeration member.
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!