views:

923

answers:

3

suppose I have an enum

[Flags]
public enum E { 
    zero = 0,
    one = 1
}

then I can write

E e;
object o = 1;
e = (E) o;

and it will work.

BUT if I try to do that at runtime, like

(o as IConvertible).ToType(typeof(E), null)

it will throw InvalidCastException.

So, is there something that I can invoke at runtime, and it will convert from int32 to enum, in the same way as if I wrote a cast as above?

A: 

How does the variable look like that you save the result of that conversion in? I.e. with which type do you declare it?

If you want to have an object variable, make it so. Instead of null, use Activator.CreateInstance to create a default instance of the enum:

object o = Activator.CreateInstance(typeof(E));
Konrad Rudolph
I want it to be Object. That is, boxed enum. The point is that the type is not known at compile time, so I don't want to declare a 'destination' variable with exact type.
artem
I see your problem now. It hasn't actually got anything to do with casting, as my code shows. Rather, the problem is the creation of an instance based on a runtime type.
Konrad Rudolph
No. The problem hasn't got anything with object creation. I have integer value, which comes from, say, xml file. The problem is:how do I assign it to that object? (again, the actual type E is coming as a Type parameter and is not known at compile type, so I can't write a cast)
artem
+4  A: 

object o = 1;
object z = Enum.ToObject(typeof(E), o); 

shahkalpesh
That's it, THANKS!
artem
A: 

You can also use

Enum.Parse(typeof(E), (int)o)
Ben Childs