Following is the method in C# to get the enum value by string
///
/// Method to get enumeration value from string value.
///
///
///
public T GetEnumValue<T>(string str) where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
throw new Exception("T must be an Enumeration type.");
}
T val = ((T[])Enum.GetValues(typeof(T)))[0];
if (!string.IsNullOrEmpty(str))
{
foreach (T enumValue in (T[])Enum.GetValues(typeof(T)))
{
if (enumValue.ToString().ToUpper().Equals(str.ToUpper()))
{
val = enumValue;
break;
}
}
}
return val;
}
Following is the method in C# to get the enum value by int.
///
/// Method to get enumeration value from int value.
///
///
///
public T GetEnumValue<T>(int intValue) where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
throw new Exception("T must be an Enumeration type.");
}
T val = ((T[])Enum.GetValues(typeof(T)))[0];
foreach (T enumValue in (T[])Enum.GetValues(typeof(T)))
{
if (Convert.ToInt32(enumValue).Equals(intValue))
{
val = enumValue;
break;
}
}
return val;
}
If I have an enum as follows:
public enum TestEnum
{
Value1 = 1,
Value2 = 2,
Value3 = 3
}
then I can make use of above methods as
TestEnum reqValue = GetEnumValue<TestEnum>("Value1"); // Output: Value1
TestEnum reqValue2 = GetEnumValue<TestEnum>(2); // OutPut: Value2
Hope this will help.