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

后端 未结 12 2650
野趣味
野趣味 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:25

    Checking for nothing/Null is the way to do it.

    Dealing with object types is not the way to go. Declare a strict type and try to cast the object to the correct type. (And use cast hint or Convert)

     private const string SESSION_VAR = "myString";
     string sSession;
     if (Session[SESSION_VAR] != null)
     {
         sSession = (string)Session[SESSION_VAR];
     }
     else
     {
         sSession = "set this";
         Session[SESSION_VAR] = sSession;
     }
    

    Sorry for any syntax violations, I am a daily VB'er

提交回复
热议问题