tags:

views:

146

answers:

4

I'm trying to dynamically set an enum based on the value in a string so far so good I don't know what I've been doing wrong. I have the following code:

public enum TagLabels : long
    {
        TurnLeft = 0x0000000000000000000030A38DB1,
        TurnRight = 0x00000000000000000000307346CC,
        LiftApproach = 0x0000000000000000000012107A8D
    }

TagLabels IDs;

string someID = "0x0000000000000000000012107A8D"; 
IDs = (TagLabels)Enum.Parse(typeof(TagLabels), someID ); //<== I get runtime error on this line

I cannot see what's wrong with what I'm doing.

A: 

Where is the string you're parsing? Aren't you trying to turn a string like "TurnLeft" into TagLabels.TurnLeft?

MSDN

n8wrl
I'm trying to use the tag string to set the ID variable
Dark Star1
+1  A: 

SomeID is a string and your enum is a long.

Try using TurnLeft instead of "0x0000000000000000000012107A8D"

Shiraz Bhaiji
+2  A: 
IDs = (TagLabels)Convert.ToInt64(someID, 16);

EDIT: You have a string that is in hex format and not a direct number. So, it needs conversion to int first.

If the Enum value exists, you can cast an int value to Enum type.

EDIT2: Changed after Marc's suggestion from Convert.ToInt32 to Convert.ToInt64

shahkalpesh
Muchas gracias padre
Dark Star1
You may want ToInt64, considering the enum is of type Int64 (long)
Marc
Thanks Marc. +1 for your suggestion.
shahkalpesh
+4  A: 

Enum.Parse is intended to convert a string representation of the symbolic name into an enum val, as in Enum.Parse("TurnLeft"). If what you have is a string giving the numeric value, then you should just parse the string as the corresponding integer type and cast it to the Enum val.

IDs = (TagLabels)long.Parse("0x0000000000000000000012107A8D");
JSBangs