tags:

views:

32466

answers:

6

What's a quick and easy way to cast an int to an enum in c#?

+97  A: 

From a string:

YourEnum foo = (YourEnum) Enum.Parse(typeof(yourEnum), yourString);

From an int:

YourEnum foo = (YourEnum)yourInt;
FlySwat
+7  A: 
int one = 1;

MyEnum e = (MyEnum)one;
abigblackman
+52  A: 

Just cast it:

MyEnum e = (MyEnum)3;

You can check if it's in range using Enum.IsDefined:

if (Enum.IsDefined(typeof(MyEnum), 3)) { ... }
Matt Hamilton
Beware you can't use Enum.IsDefined if you use the Flags attribute and the value is a combination of flags for example: Keys.L | Keys.Control
dtroy
Good point, dtroy! +1!
Matt Hamilton
A: 

Using reflection, how can I convert from a number to a enum witch type can be passed as method parameter? thanks

You should turn this into a separate question
Philippe Leybaert
MethodThatTakesEnumParameter((MyEnum)myInt);
Carl Bergquist
+1  A: 

Sometimes you have and object to the MyEnum type. Like

var MyEnumType = typeof(MyEnumType);

then:

Enum.ToObject(typeof(MyEnum), 3)
L. D.
+1  A: 

Below is a nice utility class for Enums

public static class EnumHelper
{
    public static int[] ToIntArray<T>(T[] value)
    {
        int[] result = new int[value.Length];
        for (int i = 0; i < value.Length; i++)
            result[i] = Convert.ToInt32(value[i]);
        return result;
    }

    public static T[] FromIntArray<T>(int[] value) 
    {
        T[] result = new T[value.Length];
        for (int i = 0; i < value.Length; i++)
            result[i] = (T)Enum.ToObject(typeof(T),value[i]);
        return result;
    }


    internal static T Parse<T>(string value, T defaultValue)
    {
        if (Enum.IsDefined(typeof(T), value))
            return (T) Enum.Parse(typeof (T), value);

        int num;
        if(int.TryParse(value,out num))
        {
            if (Enum.IsDefined(typeof(T), num))
                return (T)Enum.ToObject(typeof(T), num);
        }

        return defaultValue;
    }
}
Tawani