Converting an integer to a boxed enum type only known at runtime
- by Marc Gravell
Imagine we have an enum:
enum Foo { A=1,B=2,C=3 }
If the type is known at compile-time, a direct cast can be used to change between the enum-type and the underlying type (usually int):
static int GetValue() { return 2; }
...
Foo foo = (Foo)GetValue(); // becomes Foo.B
And boxing this gives a box of type Foo:
object o1 = foo;
Console.WriteLine(o1.GetType().Name); // writes Foo
(and indeed, you can box as Foo and unbox as int, or box as int and unbox as Foo quite happily)
However (the problem); if the enum type is only known at runtime things are... trickier. It is obviously trivial to box it as an int - but can I box it as Foo? (Ideally without using generics and MakeGenericMethod, which would be ugly). Convert.ChangeType throws an exception. ToString and Enum.Parse works, but is horribly inefficient.
I could look at the defined values (Enum.GetValues or Type.GetFields), but that is very hard for [Flags], and even without would require getting back to the underlying-type first (which isn't as hard, thankfully).
But; is there a more direct to get from a value of the correct underlying-type to a box of the enum-type, where the type is only known at runtime?