This code here works but forces me to cast the JSOEnum.Security
JOSEnum.SecurityLevel test = (JOSEnum.SecurityLevel)Enum.Parse(typeof(JOSEnum), "test");
This code does not work because it requires a cast.
JOSEnum.SecurityLevel test = Enum.Parse(typeof(JOSEnum.SecurityLevel), "test");
So my question is, why do I have to cast? Wouldn't the parse function take care of the type?
August 24th, 2013, 02:38 PM
Re: Enumerator Casting
Originally Posted by user87347834
Wouldn't the parJOSEnum.SecurityLevele function take care of the type?
Even though you are passing in the type using the typeof() call, the Enum.Parse method still can't return the correct type without a cast. Had the api authors had generics in .net 1.0, they probably would have written the parse method as generic. This would allow you to call Enum.Parse like:
var securityLevel = Enum.Parse<SecurityLevel>(typeof(SecurityLevel), "L1");
Unfortunately, generics weren't added until .net 2.0 so Enum.Parse wasn't written as generic, and as written, it requires a cast.
You can always write your own generic method ( or possibly even an extension method ):
public T Parse<T>(string value) where T : enum
return (T) Enum.Parse(typeof(T), value);