What is the best way to determine a session variable is null or empty in C#?

后端 未结 12 2683
野趣味
野趣味 2020-11-29 15:33

What is the best way to check for the existence of a session variable in ASP.NET C#?

I like to use String.IsNullOrEmpty() works for strings and wonder

12条回答
  •  一个人的身影
    2020-11-29 16:12

    I also like to wrap session variables in properties. The setters here are trivial, but I like to write the get methods so they have only one exit point. To do that I usually check for null and set it to a default value before returning the value of the session variable. Something like this:

    string Name
    {
       get 
       {
           if(Session["Name"] == Null)
               Session["Name"] = "Default value";
           return (string)Session["Name"];
       }
       set { Session["Name"] = value; }
    }
    

    }

提交回复
热议问题