2

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?

3 Answers 3

8

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();
Sign up to request clarification or add additional context in comments.

3 Comments

Indeed, and Enum.Parse handles that. (Though I may not have fleshed out my answer when you posted that!)
Yea, not trying to get the name of the constant to string..but the constant itself
so I just need the (MyEnum)Enum.Parse(typeof(MyEnum), Request["somevar"]. Thanks did not know about the parse yet.
2

There is built-in functionality for this task:

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

1 Comment

Hah, it seems Enum.Parse handles it:) Learned something new:)
2

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.

2 Comments

Is there a benefit to using the Enum.Parse() vs. int.Parse()? Example: ((MyEnum)Enum.Parse(typeof(MyEnum), Request["somevar"])).ToString();
@Zacharay: int.Parse is a little faster.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.