Enumerator Casting
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Enumerator Casting

  1. #1
    Join Date
    Aug 2013
    Posts
    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?

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    11,359

    Re: Enumerator Casting

    Quote Originally Posted by user87347834 View Post
    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
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center