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
2008-08-27 03:59:42
+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
2008-08-27 04:01:14
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
2009-07-31 04:49:58
Good point, dtroy! +1!
Matt Hamilton
2009-07-31 04:51:57
A:
Using reflection, how can I convert from a number to a enum witch type can be passed as method parameter? thanks
+1
A:
Sometimes you have and object to the MyEnum type. Like
var MyEnumType = typeof(MyEnumType);
then:
Enum.ToObject(typeof(MyEnum), 3)
L. D.
2010-07-02 14:41:41
+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
2010-09-07 04:42:51