How to save enum value for a session

I am creating an enum property. This property must be saved in the 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 replace this line with

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

This error is shown.

Cannot implicit convert type 'object' to 'TPageMode'

How to read Enum value from a session?

+3
source share
2 answers

Try the following:

return (TPageMode) Session["Mode"];

As the error message says, “how” cannot be used with value types that are not null. Enum.Parse would work (inefficiently) if you applied the correct type:

return (TPageMode) Enum.Parse(Session["Mode"], typeof(TPageMode));
+8
source

Code

return Session["Mode"] as TPageMode

returns an error because it is TPageModenot a reference type.

as - #. , . , null. TPageMode , null. , .

,

return (TPageMode) Session["Mode"];

, , InvalidCastException. , , .

+1

Source: https://habr.com/ru/post/1718784/


All Articles