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]

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
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)