PositiveGuy
PositiveGuy

Reputation: 47763

Return Enum Constant based on an incoming String Value

I'm going to grab the enum value from a querystring.

For instance lets say I have this enum:

Enum MyEnum
{
    Test1,
    Test2,
    Test3
}

I'm going to grab the value from an incoming querystring, so:

string myEnumStringValue = Request["somevar"];

myEnumStringValue could be "0", "1", "2"

I need to get back the actual Enum Constant based on that string value.

I could go and create a method that takes in the string and then perform a case statement

case "0":
    return MyEnum.Test1;
    break;

but there's got to be an easier or more slick way to do this?

Upvotes: 2

Views: 3146

Answers (3)

SLaks
SLaks

Reputation: 887777

You need to parse the string to get its integer value, cast the value to the Enum type, then get the enum value's name, like this:

string myEnumStringValue = ((MyEnum)int.Parse(Request["somevar"])).ToString();

EDIT: Or, you can simply call Enum.Parse. However, this should be a little bit faster.

Upvotes: 2

Petar Minchev
Petar Minchev

Reputation: 47383

There is built-in functionality for this task:

MyEnum convertedEnum = (MyEnum) Enum.Parse(typeof(MyEnum), myEnumStringValue);

Upvotes: 2

Jeff Sternal
Jeff Sternal

Reputation: 48623

Take a look at Enum.Parse, which can convert names or values to the correct enum value.

Once you have that, cast the result to MyEnum and call ToString() to get the name of the constant.

return ((MyEnum)Enum.Parse(typeof(MyEnum), Request["somevar"])).ToString();

Upvotes: 8

Related Questions