Once constant annoyance I’ve had with C# has been parsing a string into an enum.
Original C#:
MyEnum e = (MyEnum) Enum.Parse(typeof(MyEnum), "myvalue");
Using generics let you write a function to help:
public static T ParseEnum<T>(string name) {
return (T)Enum.Parse(typeof(T), name);
}
So then you can simply* say:
MyEnum e = ParseEnum<MyEnum>("myvalue");
A little nicer, but still annoying.
*: simply for C#
Alex | 19-Feb-07 at 2:04 am | Permalink
Thanks for idea
Rob | 05-Mar-09 at 9:42 am | Permalink
Hey just came across this snippet.
Very handy. I’ve made it a little more robust, and turned it into an extension method:
public static T ParseToEnum(this string name)
{
if (false == typeof(T).IsEnum)
throw new NotSupportedException(typeof(T).Name + ” must be an Enum”);
if(false == Enum.IsDefined(typeof(T), name))
throw new ArgumentException(string.Format(“{0} is not defined in type of enum {1}”, name, typeof(T).Name));
return (T)Enum.Parse(typeof(T), name);
}
And some unit tests for it:
[Test]
public void ParseToEnum_ValidStringValidEnum_ReturnsSuccess()
{
var e = “Success”.ParseToEnum();
Assert.AreEqual(WebExceptionStatus.Success, e);
}
[Test, ExpectedException("System.NotSupportedException")]
public void ParseToEnum_TypeIsNotAnEnum_ThrowsException()
{
var e = “Success”.ParseToEnum();
}
[Test, ExpectedException("System.ArgumentException")]
public void ParseToEnum_StringNotDefinedInEnum_ThrowsException()
{
var e = “ThisDoesNotExist”.ParseToEnum();
}
Rob Volk | 18-Feb-10 at 12:20 pm | Permalink
The extension method is what I was looking for. Works great. I love open source development via blog comments! thanks guys.
Rob Volk | 18-Feb-10 at 12:30 pm | Permalink
BTW – you forgot the generic declaration on the method signature. Should be:
public static T ParseToEnum(this string name)
ryan | 18-Feb-10 at 12:45 pm | Permalink
@Rob Volk: I bet wordpress is eating the angle brackets