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<T>(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<T>(str, true, out val) ? val : default(T);
}
public static T GetEnumValue<T>(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.
Here is an example to get string/value
public enum Suit
{
Spades = 0x10,
Hearts = 0x11,
Clubs = 0x12,
Diamonds = 0x13
}
private void print_suit()
{
foreach (var _suit in Enum.GetValues(typeof(Suit)))
{
int suitValue = (byte)(Suit)Enum.Parse(typeof(Suit), _suit.ToString());
MessageBox.Show(_suit.ToString() + " value is 0x" + suitValue.ToString("X2"));
}
}
Result of Message Boxes
Spade value is 0x10
Hearts value is 0x11
Clubs value is 0x12
Diamonds value is 0x13
You could use following method to do that:
public static Output GetEnumItem<Output, Input>(Input input)
{
//Output type checking...
if (typeof(Output).BaseType != typeof(Enum))
throw new Exception("Exception message...");
//Input type checking: string type
if (typeof(Input) == typeof(string))
return (Output)Enum.Parse(typeof(Output), (dynamic)input);
//Input type checking: Integer type
if (typeof(Input) == typeof(Int16) ||
typeof(Input) == typeof(Int32) ||
typeof(Input) == typeof(Int64))
return (Output)(dynamic)input;
throw new Exception("Exception message...");
}
Note:this method only is a sample and you can improve it.
I think you forgot the generic type definition:
public T GetEnumValue<T>(int intValue) where T : struct, IConvertible // <T> added
and you can improve it to be most convinient like e.g.:
public static T ToEnum<T>(this string enumValue) : where T : struct, IConvertible
{
return (T)Enum.Parse(typeof(T), enumValue);
}
then you can do:
TestEnum reqValue = "Value1".ToEnum<TestEnum>();
No, you don't want a generic method. This is much easier:
MyEnum myEnum = (MyEnum)myInt;
MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), myString);
I think it will also be faster.
Try something like this
public static TestEnum GetMyEnum(this string title)
{
EnumBookType st;
Enum.TryParse(title, out st);
return st;
}
So you can do
TestEnum en = "Value1".GetMyEnum();