How can I get the enum value if I have the enum string or enum int value. eg: If i have an enum as follows:
public enum TestEnum
{
Value1 = 1,
Value
Could be much simpler if you use TryParse or Parse and ToObject methods.
public static class EnumHelper
{
public static T GetEnumValue(string str) where T : struct, IConvertible
{
Type enumType = typeof(T);
if (!enumType.IsEnum)
{
throw new Exception("T must be an Enumeration type.");
}
T val;
return Enum.TryParse(str, true, out val) ? val : default(T);
}
public static T GetEnumValue(int intValue) where T : struct, IConvertible
{
Type enumType = typeof(T);
if (!enumType.IsEnum)
{
throw new Exception("T must be an Enumeration type.");
}
return (T)Enum.ToObject(enumType, intValue);
}
}
As noted by @chrfin in comments, you can make it an extension method very easily just by adding this before the parameter type which can be handy.