Dark Star1
Dark Star1

Reputation: 7403

Why is my enum.Parse method failing?

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.

Upvotes: 0

Views: 557

Answers (4)

shahkalpesh
shahkalpesh

Reputation: 33474

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

Upvotes: 3

Shiraz Bhaiji
Shiraz Bhaiji

Reputation: 65391

SomeID is a string and your enum is a long.

Try using TurnLeft instead of "0x0000000000000000000012107A8D"

Upvotes: 1

JSBձոգչ
JSBձոգչ

Reputation: 41378

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");

Upvotes: 4

n8wrl
n8wrl

Reputation: 19765

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

MSDN

Upvotes: 0

Related Questions