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());
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>();
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!
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With