-
August 22nd, 2013, 06:18 PM
#1
Enumerator Casting
Im trying to figure out why the following is making me cast the enumerator.
Here is the enumerator:
Code:
public enum SecurityLevel { L1 = 0, L2, L3, L4, L5 }
This code here works but forces me to cast the JSOEnum.Security
Code:
JOSEnum.SecurityLevel test = (JOSEnum.SecurityLevel)Enum.Parse(typeof(JOSEnum), "test");
This code does not work because it requires a cast.
Code:
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
#2
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:
Code:
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 ):
Code:
public T Parse<T>(string value) where T : enum
{
return (T) Enum.Parse(typeof(T), value);
}
This would allow...
Code:
var securityLevel = Parse<SecurityLevel>("L1");
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|