Christopher Bennage

Sponsors

The Lounge

Wicked Cool Jobs

Syndication

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
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

Posted 09-13-2007 10:51 PM by Christopher Bennage
Filed under: ,

[Advertisement]

Comments

Bill wrote re: My new little friend, Enum<T>
on 09-14-2007 1:29 AM

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

Michal Grzegorzewski wrote re: My new little friend, Enum<T>
on 09-14-2007 3:48 AM

small correction

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

Depechie wrote re: My new little friend, Enum<T>
on 09-14-2007 4:44 AM

Damn... that's just plain brilliant !

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

PartialClass wrote re: My new little friend, Enum<T>
on 09-14-2007 5:25 AM

a nice helper class!

Christopher Bennage wrote re: My new little friend, Enum<T>
on 09-14-2007 8:43 AM

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

DotNetKicks.com wrote My new little friend, Enum
on 09-14-2007 8:46 AM

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

Thomas Watson wrote re: My new little friend, Enum<T>
on 09-14-2007 9:33 AM

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)

Alvin Ashcraft wrote re: My new little friend, Enum<T>
on 09-14-2007 12:30 PM
Great little helper class! Thanks, I think this is going to be one of my favs.
Kirill Osenkov wrote re: My new little friend, Enum<T>
on 09-14-2007 2:14 PM

Nice ideas folks!

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

.Net Adventures wrote Interesting articles (September 15)
on 09-15-2007 10:30 AM

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

14 Links Today (2007-09-15) wrote 14 Links Today (2007-09-15)
on 09-15-2007 11:21 AM

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

Kirill Osenkov wrote re: My new little friend, Enum<T>
on 09-15-2007 2:05 PM
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
Weekly Link Post 7 « Rhonda Tipton’s WebLog wrote Weekly Link Post 7 &laquo; Rhonda Tipton&#8217;s WebLog
on 09-16-2007 4:35 PM

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

Patrick Steele's .NET Blog wrote The Beauty Is In The Simplicity
on 09-17-2007 6:08 PM

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

Patrick Steele wrote The Beauty Is In The Simplicity
on 09-17-2007 6:10 PM

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

Elan's Aggregated Blogs wrote The Beauty Is In The Simplicity
on 09-17-2007 6:45 PM

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

sotto wrote re: My new little friend, Enum<T>
on 09-19-2007 2:29 AM
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)
Carl wrote re: My new little friend, Enum<T>
on 09-19-2007 5:25 AM
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
Joe Niland wrote re: My new little friend, Enum<T>
on 09-19-2007 11:56 PM
I converted this to vb.net at http://converter.telerik.com/ and it worked out of the box. Thanks Christopher
Jimbo wrote re: My new little friend, Enum<T>
on 09-26-2007 5:22 AM
Might be an idea to make it thread safe?
Jason Bock wrote re: My new little friend, Enum<T>
on 09-26-2007 8:10 AM
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 :)
Asp.Net Control For Google Charts « Spontaneous Publicity wrote Asp.Net Control For Google Charts &laquo; Spontaneous Publicity
on 12-09-2007 3:43 AM

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

Developer Blogs wrote The Beauty Is In The Simplicity
on 12-21-2007 10:44 AM

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

Associating Strings with enums in C# « Spontaneous Publicity wrote Associating Strings with enums in C# &laquo; Spontaneous Publicity
on 01-17-2008 4:51 PM

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

http://devlicio.us/blogs/christopher_bennage/archive/2007/09/13/my-new-little-friend-enum-lt-t-gt.aspx wrote http://devlicio.us/blogs/christopher_bennage/archive/2007/09/13/my-new-little-friend-enum-lt-t-gt.aspx
on 03-21-2008 2:23 AM
Peter's Software House wrote Loving Extensions
on 06-30-2008 6:15 AM

I saw a post recently where Christopher Bennage talks about his little friend, Enum&lt;T&gt; .&#160;&#160;

Interesting articles (September 15) | devintelligence.com wrote Interesting articles (September 15) | devintelligence.com
on 07-27-2008 7:02 AM

Pingback from  Interesting articles (September 15) | devintelligence.com

Amoxicillin. wrote Amoxicillin anti-inflammatory.
on 05-29-2009 7:48 PM

Amoxicillin rx655 syphilis. Amoxicillin for your pet. Amoxicillin pregnancy. Taking amoxicillin while pregnant.

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)

CodeBetter.Com