Getting Enum value via reflection

Solution 1:

Great question Mat.

The scenario of the question is this:

You have some unknown enum type and some unknown value of that type and you want to get the underlying numeric value of that unknown value.

This is the one-line way of doing this using reflection:

object underlyingValue = Convert.ChangeType(value, Enum.GetUnderlyingType(value.GetType()));

If value happens to be TestEnum.TestTwo, then value.GetType() would be equal to typeof(TestEnum), Enum.GetUnderlyingType(value.GetType()) would be equal to typeof(int) and value would be 3 (boxed; see http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx for more details about boxing and unboxing values).

Why would one ever need to write such code? In my case, I have a routine that copies values from a viewmodel to a model. I use this in all my handlers in an ASP.NET MVC project as part of a very clean and elegant architecture for writing handlers that do not have the security problems the handlers generated by the Microsoft templates do.

The model is generated by the Entity Framework from the database and it contains a field of type int. The viewmodel has a field of some enum type, let's call it RecordStatus, which I have defined elsewhere in my project. I decided to support enums fully in my framework. But now there is a mismatch between the type of the field in the model and the type of the corresponding field in the viewmodel. My code detects this and converts the enum to an int using the code similar to the one-liner given above.

Solution 2:

You can use the System.Enum helpers:

System.Type enumType = typeof(TestEnum);
System.Type enumUnderlyingType = System.Enum.GetUnderlyingType(enumType);
System.Array enumValues = System.Enum.GetValues(enumType);

for (int i=0; i < enumValues.Length; i++)
{
    // Retrieve the value of the ith enum item.
    object value = enumValues.GetValue(i);

    // Convert the value to its underlying type (int, byte, long, ...)
    object underlyingValue = System.Convert.ChangeType(value, enumUnderlyingType);

    System.Console.WriteLine(underlyingValue);
}

Outputs

3
4

Solution 3:

Full code : How to Get Enum Values with Reflection in C#

MemberInfo[] memberInfos = typeof(MyEnum).GetMembers(BindingFlags.Public | BindingFlags.Static);
string alerta = "";
for (int i = 0; i < memberInfos.Length; i++) {
alerta += memberInfos[i].Name + " - ";
alerta += memberInfos[i].GetType().Name + "\n";
}

Solution 4:

Why do you need reflection?

int value = (int)TestEnum.TestOne;

Solution 5:

For your requirement it's as simple as people already pointed it out. Just cast the enum object to int and you'd get the numeric value of the enum.

int value = (int) TestEnum.TestOne;

However, if there is a need to mix-down enum values with | (bitwise OR) e.g.

var value = TestEnum.TestOne | TestEnum.TestTwo;

and you wish to get what options that mixed-down value represents, here is how you could do it (note: this is for enums that represented by int values intended to take advantage of bitwise operatations) :

first, get the enum options along with their values in a dictionary.

var all_options_dic = typeof(TestEnum).GetEnumValues().Cast<object>().ToDictionary(k=>k.ToString(), v=>(int) v);

Filter the dictionary to return only the mixed-down options.

var filtered = all_options_dic.Where(x => (x.Value & (int) options) != 0).ToDictionary(k=>k.Key, v=>v.Value);

do whatever logic with your options. e.g. printing them, turning them to List, etc..:

foreach (var key in filtered.Keys)
        {
            Console.WriteLine(key + " = " + filtered[key]);
        }

hope this helps.