Number of times I have come across the situation where I wanted to convert a string into enum. Using switch case statements to return the enum becomes quite tedious when there are many items. Recently I found a static method in
Enum class which replaces these switch statements and is a big time saver.
public static object Enum.Parse(System.Type enumType, string value)
Look at the following code
enum Days
{
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}
//........
string val = "Tuesday";
Days day = Enum.Parse(typeof(Days), val);
Console.WriteLine("Day Value: {0}", day.ToString());
//You can also ignore the case of the string being parsed
//by using the following method
public static object Parse(Type enumType, string value, bool ignoreCase);
Parsing an invalid day will throw an Argument Exception. So it is always a good idea to check if the enum exists, look at the following code:
string val = "Tuesday";
Day day;
if(Enum.IsDefined(typeof(Days), val))
day = Enum.Parse(typeof(Days), val);
Unfortunately,
Enum.IsDefined() does not provide ignore case option.
No comments:
Post a Comment