Devlicio.us
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @devlicious

Christopher Bennage

Musings and revelations on C#, .NET, and other related technologies.


My new little friend, Enum<T>

I hate ugly code like this:

MyEnum enumValue = (MyEnum) Enum.Parse(typeof (MyEnum), stringValue);

Too many casts for my taste. Here's my answer (and yes it's so simple that I am embarrassed to post it, but just in case you haven't thought of it yet...)

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

    public static IList<T> GetValues()
    {
        IList<T> list = new List<T>();
        foreach (object value in Enum.GetValues(typeof (T)))
        {
            list.Add((T) value);
        }
        return list;
    }
}

So the ugliness is converted to

MyEnum enumValue = Enum<MyEnum>.Parse(stringValue);
kick it on DotNetKicks.com


Comments

Bill said:

I totally agree. I made a class a while back that does that and I added in some other enum stuff that I got sick of doing over and over.  One of these days I'll post an updated version.

rodenbaugh.net/.../Enum-Helper-Class-Using-Generics.aspx

# September 14, 2007 1:29 AM

Michal Grzegorzewski said:

small correction

MyEnum enumValue = Enum<MyEnum>.Parse(stringValue);

# September 14, 2007 3:48 AM

Depechie said:

Damn... that's just plain brilliant !

I've also got lots of those Enum casts in my code... going to change it :)

# September 14, 2007 4:44 AM

PartialClass said:

a nice helper class!

# September 14, 2007 5:25 AM

Christopher Bennage said:

@Michal.  Thanks.  I had to convert the <> tags manually for the generics and I missed those.

# September 14, 2007 8:43 AM

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# September 14, 2007 8:46 AM

Thomas Watson said:

I recently did something similar with an extension method:

public static class EnumExtensionMethods

   {

       /// <summary>

       /// This method attempts to convert the Enum Value to the given Enum type and value. Basically saves specifically casting and geting

       /// the type

       /// </summary>

       /// <typeparam name="T">This is the type of enum to convert to</typeparam>

       /// <param name="pEnum">This is the object being extended</param>

       /// <param name="pEnumValueToConvert">The enum to convert to</param>

       /// <returns>An enum of the type T if a match can be found</returns>

       public static T ConvertToEnum<T>(this Enum pEnum, T pEnumValueToConvertToType)

       {

           try

           {

               return (T)Enum.Parse(typeof(T), pEnum.ToString());

           }

           catch (Exception)

           {

               throw new FormatException("Unable to Convert Enum values, most likely cause is value(" + pEnum.ToString() + ") is missing from the target enum");

           }

       }//end extension method

   }

so now the code usage is this:

to.CurrentOperation = from.CurrentOperation.ConvertToEnum(to.CurrentOperation);

where to and from are different enums (Business Entity versus Presenation Object... code taked from a translator class)

# September 14, 2007 9:33 AM

Alvin Ashcraft said:

Great little helper class! Thanks, I think this is going to be one of my favs.
# September 14, 2007 12:30 PM

Kirill Osenkov said:

Nice ideas folks!

One could also make an extension method on the string class, like this: <a href="kirillosenkov.blogspot.com/.../a>

# September 14, 2007 2:14 PM

.Net Adventures said:

My new little friend, Enum&lt;T&gt; by Christopher Bennage My Slides/Samples from MIX:UK - Building Silverlight

# September 15, 2007 10:30 AM

14 Links Today (2007-09-15) said:

Pingback from  14 Links Today (2007-09-15)

# September 15, 2007 11:21 AM

Kirill Osenkov said:

Sorry, the link got messed up for some reason: http://kirillosenkov.blogspot.com/2007/09/making-c-enums-more-usable-parse-method.html http://kirillosenkov.blogspot.com/2007/09/making-c-enums-more-usable-parse-method.html
# September 15, 2007 2:05 PM

Weekly Link Post 7 « Rhonda Tipton’s WebLog said:

Pingback from  Weekly Link Post 7 &laquo; Rhonda Tipton&#8217;s WebLog

# September 16, 2007 4:35 PM

Patrick Steele's .NET Blog said:

This is so simple, it's beautiful. A very elegant way of dealing with Enums.

# September 17, 2007 6:08 PM

Patrick Steele said:

This is so simple, it&#39;s beautiful. A very elegant way of dealing with Enums.

# September 17, 2007 6:10 PM

Elan's Aggregated Blogs said:

This is so simple, it&#39;s beautiful. A very elegant way of dealing with Enums.

# September 17, 2007 6:45 PM

sotto said:

When you write this helperclass in c++ (.net), you could even restrict the T to only accept enums. But then you'd need to reference the c++ dll ... too bad c# doesn't allow this. (at least in 2.0 it didn't, don't know 'bout 3.x)
# September 19, 2007 2:29 AM

Carl said:

Beautiful, thanks. I also used it in one of my few vb.net projects: Public Class [Enum](Of T) Public Shared Function Parse(ByVal value As String) As T Return CType([Enum].Parse(GetType(T), value), T) End Function Public Shared Function GetValues() As IList(Of T) Dim list As IList(Of T) list = New List(Of T) For Each value As Object In [Enum].GetValues(GetType(T)) list.Add(CType(value, T)) Next Return list End Function End Class If it helps anyone, obviously you still need to distinguish it from the reserved keyword - [Enum](Of MyEnum).Parse() The thing that makes this nice in VB is that the syntax for casting is horrific, so this improves readability much more than it does in the C# version. MyEnum e = CType([Enum].Parse(GetType(MyEnum),myString), MyEnum) becomes MyEnum e = [Enum](Of MyEnum).Parse(myString) That deserves a whole bunch of loving in my eyes. Carl
# September 19, 2007 5:25 AM

Joe Niland said:

I converted this to vb.net at http://converter.telerik.com/ and it worked out of the box. Thanks Christopher
# September 19, 2007 11:56 PM

Jimbo said:

Might be an idea to make it thread safe?
# September 26, 2007 5:22 AM

Jason Bock said:

I just wrote an enum converter that uses nullable types as the return value: http://www.jasonbock.net/JB/Default.aspx?blog=entry.481aeddbeeda4e889254d9631610e8b4 I think you inspired me without me realizing it :)
# September 26, 2007 8:10 AM

Asp.Net Control For Google Charts « Spontaneous Publicity said:

Pingback from  Asp.Net Control For Google Charts &laquo; Spontaneous Publicity

# December 9, 2007 3:43 AM

Developer Blogs said:

This is so simple, it&#39;s beautiful. A very elegant way of dealing with Enums.

# December 21, 2007 10:44 AM

Associating Strings with enums in C# « Spontaneous Publicity said:

Pingback from  Associating Strings with enums in C# &laquo; Spontaneous Publicity

# January 17, 2008 4:51 PM

About Christopher Bennage

Christopher is a software developer and consultant at Blue Spire Consulting, a company he co-founded with Rob Eisenberg in 2006. His interests include programming, liberal education, truth, beauty, and number of deceased British authors (C. S. Lewis, G. K. Chesterton, and most recently Owen Barfield.) He lives in Tallahassee, FL with his wife and two children and still prefers to play as the Night Elves in WarCraft 3. Stuff You Need to CodeBetter!

Red-Gate!