views:

279

answers:

2

I'm creating enum property. This property should saved into session. My code is here

public enum TPageMode { Edit=1,View=2,Custom=3}

       protected TPageMode Mode { 
            get{
                if (Session["Mode"] == null)
                    return TPageMode.Edit;
                else
                {
                    return Session["Mode"] as TPageMode; // This row is problem
                }                
            }
            set {
                Session["Mode"] = value;
            } 
        }

compiler release error on return Session["Mode"] as TPageMode

The as operator must be used with a reference type or nullable type

When i replacing this row to

return Enum.Parse(typeof(TPageMode), Session["Mode"].ToString());

This error shown

Cannot implicit convert type 'object' to 'TPageMode'

How to read Enum value from session?

+4  A: 

Try this:

return (TPageMode) Session["Mode"];

As the error message says, "as" can't be used with non-nullable value types. Enum.Parse would have worked (inefficiently) if you'd then cast to the right type:

return (TPageMode) Enum.Parse(Session["Mode"], typeof(TPageMode));
Jon Skeet
Oh thanks. was very simple :)
ebattulga
A: 

The code

return Session["Mode"] as TPageMode

returns an error, because TPageMode is not a reference type.

The as operator is a special kind of reflection-based type conversion in C#. It checks whether the left-hand-side of operator can be converted to the type on the right-hand-side. If the conversion is not possible, the expression returns null. Since TPageMode is an enum and is based on value types, it cannot hold the value null. As such, the operator cannot be used in this example.

To perform this type conversion, simply use

return (TPageMode) Session["Mode"];

Using this syntax, if the conversion is not possible, an InvalidCastException is thrown by the runtime. Use this syntax when you are confident the conversion should always be possible in normal circumstances.

Programming Hero