tags:

views:

151

answers:

2

I have the following code.

private Enum MyEnum
{
    VALUE1=5, VALUE2=4, VALUE3=3, VALUE4=2, VALUE5=1
}

protected void Page_Load(object sender, EventArgs e)
{
    Session["EnumValue"] = "VALUE1";
    MyEnum test = (MyEnum) Session["EnumValue"];
}

In the page load, after the casting i have the value of the variable 'test' = 'VALUE2'.

I am expecting it to get test ='VALUE1'. Is there anything wrong with the code

+6  A: 

You can't simply cast the string value back into the Enum, you have to parse it:

MyEnum enumValue = (MyEnum) Enum.Parse(typeof(MyEnum), (string)Session["EnumValue"]);
Cory Larson
ok. The code is not showing any error. Is it the normal behaviour?
Ashok
Normally you would do something like Joop's answer, using the value of the enum and not the string.
Cory Larson
+2  A: 

Why are you working with a string an not with the enum? Like:

private Enum MyEnum
{
     VALUE1=5, VALUE2=4, VALUE3=3, VALUE4=2, VALUE5=1
}

protected void Page_Load(object sender, EventArgs e)
{
    Session["EnumValue"] = MyEnum.VALUE1;
    MyEnum test = (MyEnum) Session["EnumValue"];
}
Joop