I have an enumeration that is a member variable of an object. I don’t know the enumeration’s exact type, only that it is derived from System.Enum. I want to set the enumeration’s underlying numeric value. In other words:
Enum e;
// ...
e = 42; // Doesn't comple
Is this possible? Can it be done with reflection?
Edit 1: The enum is part of a larger data structure, so creating a new value using Enum.ToObject() is not suitable.
Edit 2: Clarified that the enum is a member variable of an object.
Edit 3: Since a few commenters have asked for more context, heres a summary: I have some general-purpose code that is supposed to associate UI controls (text boxes, etc) with corresponding fields in an object data model. When the UI changes the model is updated, and vice-versa. I was looking at extending this to map between combo boxes and enumerations; where the enum would be set to the index of the selected combo entry. Setting the selected item from the enum’s underlying value is trivial, but the reverse of this is where the problem occurs. I was fairly sure that this wasn’t going to be possible, but thought it was worth asking.
You need to know the enum’s
Typeat runtime, even if you don’t know it at compile-time – bacauseEnumis a boxed value, and in order to box something you need to have access to the type (so that.GetType()returns the right thing); for example, doing this at runtime: