How can an int
be cast to an enum
in C#?
For numeric values, this is safer as it will return an object no matter what:
public static class EnumEx
{
static public bool TryConvert(int value, out T result)
{
result = default(T);
bool success = Enum.IsDefined(typeof(T), value);
if (success)
{
result = (T)Enum.ToObject(typeof(T), value);
}
return success;
}
}