Sunday, August 03, 2008

image_thumb1

I had a problem where I needed to get an Enum, but all I had to work from was a string value of that Enum.

I’m not sure this is the best way to convert a string to an Enum. And that is one reason why I wanted to post this on my blog, so others could provide feedback and ideas. The other reason is so others can learn from what we know (and I’ll have it somewhere for the next time I need it Open-mouthed).

There is two pieces of useful information below. One is the Enum.Parse() method exists. And the other is a neat trick to get around having to deal with Enum.Parse()’s Type parameter.

Note: the method and the extension method will work in later versions of .NET and .NET Compact Framework.

Show me the method:

   1: public static T StringToEnum<T>(this string name)
   2: {
   3:     return (T)Enum.Parse(typeof(T), name, true);
   4: }

Chublogga, one of our readers, asked could the StringToEnum method be made into an extension method. It can, see below.

Show me the extension method:

   1: using System;
   2: using System.Linq;
   3: using System.Collections.Generic;
   4: using System.Text;
   5: using System.Text.RegularExpressions;
   6:  
   7: namespace CraftExtensions
   8: {
   9:     public static class CraftExtensions
  10:     {
  11:         public static T StringToEnum<T>(this string name)
  12:         {
  13:             return (T)Enum.Parse(typeof(T), name, true);
  14:         }
  15:     } 
  16: }

Sunday, August 03, 2008 12:12:30 (Eastern Standard Time, UTC-05:00)  #    Comments [2]  |  Trackback Tracked by:
"http://www.cjcraft.com/blog/2008/08/03/ProblemSolvedHowToGetAnEnumFromAString.a... [Pingback]

Theme design by Jelle Druyts

Pick a theme: