Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegantly parsing C# Enums

Tags:

c#

enums

Does anyone have a more elegant solution to parsing enums? The following just seems like a mess to me.

UserType userType = (UserType)Enum.Parse(typeof(UserType), iUserType.ToString());
like image 579
josh Avatar asked Jul 31 '12 14:07

josh


3 Answers

You can create an extesion method like this

public static class EnumExtensions
{
    public static T ToEnum<T>(this string s)
    {
        return (T)Enum.Parse(typeof(T), s);
    }
}

then in code you can use it this way (MyEnum contains values A and B):

string s = "B";
MyEnum e = s.ToEnum<MyEnum>();
like image 50
Mones Avatar answered Oct 07 '22 08:10

Mones


I often make a generic helper for it:

public static T ParseEnum<T>(string value) where T:struct
{
    return (T)Enum.Parse(typeof(T), value);
}

You can combine that with Jon Skeet's Unstrained Melody (or any other post IL processor) to get a proper type constraint on an enum, but that is optional.

Then you can use it like this:

var enumValue = ParseEnum<UserType>(iUserType.ToString());

The .NET Framework 4.0 also comes with Enum.TryParse which also offers a similar syntax, and offers a way to handle if the parse fails. For example:

UserType userType;
if (Enum.TryParse<UserType>(iUserType.ToString(), out userType))
{
    //Yay! Parse succeeded. The userType variable has the value.
}
else
{
    //Oh noes! The parse failed!
}
like image 33
vcsjones Avatar answered Oct 07 '22 07:10

vcsjones


Oh I came across Tyler Brinkley's Enums.NET library which does this and more!

This other StackOverflow answer Generic version of Enum.Parse in C# led to Jon Skeet's Unconstrained Melody library site, where directs us to Enums.NET instead. Wow.

like image 26
Colin Avatar answered Oct 07 '22 06:10

Colin