Not too long ago, I talked about Extension Methods in .NET 3.5 and also about a way to provide data binding an enum type with descriptions. Today, Simo talked about how often he forgets the syntax of parsing a string value to it's Enum value. In his post, he refers to a generic Enum parse method that Scott Watermasysk created just over a year ago (in 2006). In Scott's post, Kenny Kerr points back to his article (from 2005) about how to create a generic parse method in C++/CLI.
Reading through all of these posts started me thinking about the EnumHelper class in my article and how nice it would be to provide an EnumParse method as part of any String value. This is where the simplicity of extension methods really starts to show.
Taking the functions created by both Scott and Kenny, I created a derivative of them as an extension method on the String class. These functions look like
1: public static T EnumParse<T>(this string value)
3: return EnumHelper.EnumParse<T>(value, false);
6: public static T EnumParse<T>(this string value, bool ignoreCase)
8: if (value == null)
10: throw new ArgumentNullException("value");
13: value = value.Trim();
15: if (value.Length == 0)
17: throw new ArgumentException("Must specify valid information for parsing in the string.", "value");
20: Type t = typeof(T);
22: if (!t.IsEnum)
24: throw new ArgumentException("Type provided must be an Enum.", "T");
27: T enumType = (T)Enum.Parse(t, value, ignoreCase);
28: return enumType;
I think the extension method version provides a lot of benefits over the versions proposed by Scott W. and Kenny, namely by providing a natural extension to the String class and simplifying the calling syntax.
In order to use either of these functions, you can simply do this:
1: string stringValue = "Last14";
3: // Using the .NET 3.5 extension methods syntax
4: SimpleEnum enumVal2 = stringValue.EnumParse<SimpleEnum>(true);
6: // Exact same function, but using the older "helper class" style
7: SimpleEnum enumVal3 = EnumHelper.EnumParse<SimpleEnum>(stringValue, true);
9: // Using the standard Enum.Parse method
10: SimpleEnum enumVal = (SimpleEnum)Enum.Parse(typeof(SimpleEnum), stringValue);
As you can see, using the extension methods syntax greatly simplifies the calling code and provides the method on the String itself. Using the older "helper class" style of calling syntax is exactly the same as what Scott W. and Kenny provide, and is still easier than using the standard Enum.Parse method.
While this solution doesn't provide the ultimate syntax, which would simply be:
1: SimpleEnum enumVal = Enum.Parse<SimpleEnum>(stringValue);
It does provide an alternative that is almost as easy.
(This example assumes the static class is named EnumHelper and uses the SimpleEnum type defined in both my article and blog post.)