Scott Dorman

ephemeral segment

  Home  |   Contact  |   Syndication    |   Login
  571 Posts | 10 Stories | 641 Comments | 51 Trackbacks

News


Post Categories

Image Galleries



Creative Commons License


Microsoft MVP


MCP Profile


Locations of visitors to this page

Subscribers to this feed

TwitterCounter for @sdorman

View blog authority

Add to Technorati Favorites

Windows Live Alerts

AddThis Social Bookmark Button

LinkedIn profile

Community Credit profile

The Code Project

Follow me on Twitter

Get Free Shots from Snap.com

Community Credit Hall of Fame

Get Feedghost

Xobni outlook add-in for your inbox

Windows Live Translator


Support This Site

Tag Cloud


Article Categories

Archives

Post Categories

Image Galleries

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)
   2: {
   3:     return EnumHelper.EnumParse<T>(value, false);
   4: }
   5:  
   6: public static T EnumParse<T>(this string value, bool ignoreCase)
   7: {
   8:     if (value == null)
   9:     {
  10:         throw new ArgumentNullException("value");
  11:     }
  12:  
  13:     value = value.Trim();
  14:  
  15:     if (value.Length == 0)
  16:     {
  17:         throw new ArgumentException("Must specify valid information for parsing in the string.", "value");
  18:     }
  19:  
  20:     Type t = typeof(T);
  21:  
  22:     if (!t.IsEnum)
  23:     {
  24:         throw new ArgumentException("Type provided must be an Enum.", "T");
  25:     }
  26:  
  27:     T enumType = (T)Enum.Parse(t, value, ignoreCase);
  28:     return enumType;
  29: }

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";
   2:  
   3: // Using the .NET 3.5 extension methods syntax
   4: SimpleEnum enumVal2 = stringValue.EnumParse<SimpleEnum>(true);
   5:  
   6: // Exact same function, but using the older "helper class" style
   7: SimpleEnum enumVal3 = EnumHelper.EnumParse<SimpleEnum>(stringValue, true);
   8:  
   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.)

posted on Tuesday, September 25, 2007 3:32 PM

Feedback

# re: Generic Enum Parsing with Extension Methods 9/26/2008 5:22 AM Jerome L
if you think this is the ultimate syntax, i think this one would suit you as well:

SimpleEnum enumVal = Enum<SimpleEnum>.Parse(stringValue);

it's obtained by this code and as the added value to work from visual 2005:

/// <summary>
/// Enum extension for less ugly parse code
/// </summary>
/// <typeparam name="T"></typeparam>
public static class Enum<T>
{

public static T Parse(string value)
{
return (T)Enum.Parse(typeof(T), value);
}
}

Cheers,
Jerome

# re: Generic Enum Parsing with Extension Methods 11/15/2008 10:24 PM Scott
Jerome, I think that syntax would work just as well. Thanks!

# re: Generic Enum Parsing with Extension Methods 1/15/2009 7:14 AM Samin
I would rather like to use
SimpleEnum.Parse(stringValue); via a generic extension method but Enum is not allowed as generic constraint.

# re: Generic Enum Parsing with Extension Methods 1/15/2009 9:43 AM Scott
@Samin, Enum is not allowed as a generic constraint but struct is, in which case you could test to ensure that the type is an enum type. The drawback is that the Parse extension method would then appear on any struct which probably isn't desirable unless your Parse method was very intelligent and could figure out what "parse" meant for the different valid data types.

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: