Parsing strings to enums
Not something that's needed very often but sometimes we can need to get an enum value from a string, perhaps a value returned from an API you have no control over.
In general, parsing a string to an enum can be done using either
(EnumType)Enum.Parse(typeof(EnumType), stringToConvert);
or
(EnumType)Enum.Parse(typeof(EnumType), stringToConvert, ignoreCase);
This can be used to create an extension method allowing any string to be converted to an enum of any specified type.
/// <summary>
/// Parses a string into an enumeration of Type T
/// </summary>
/// <typeparam name="T">The Enumerator Type</typeparam>
/// <param name="s">The string to parse</param>
/// <param name="defaultValue">The default enumerator to use if the string cannot be parsed</param>
/// <returns>A enumeration of Type T</returns>
public static T ToEnum<T>(this string s, T defaultValue)
{
if (string.IsNullOrEmpty(s))
{
return defaultValue;
}
try
{
return (T)Enum.Parse(typeof(T), s, true);
}
catch (ArgumentException ex)
{
return defaultValue;
}
}
As the default value specifies the enum type, it isn't necessary to explicitly identify the enum type we wish to cast to.
An example would be to convert the name of a day to the appropriate DayOfWeek enum
string day = "Wednesday";
var dayOfWeek = day.ToEnum(DayOfWeek.Monday);
// dayOfWeek = DayOfWeek.Wednesday
string day = "wednesday";
var dayOfWeek = day.ToEnum(DayOfWeek.Monday);
// dayOfWeek = DayOfWeek.Wednesday
string invalidDay = "Wednesdayy";
var dayOfWeek = invalidDay.ToEnum(DayOfWeek.Monday);
// dayOfWeek = DayOfWeek.Monday
An advantage of this approach is that we can specify a default enum which will be used in case a parsing fails as in the final example above