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

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

    The 'as' notation in c# 3.0 is very clean. Since all session variables are nullable objects, this lets you grab the value and put it into your own typed variable without worry of throwing an exception. Most objects can be handled this way.

    string mySessionVar = Session["mySessionVar"] as string;
    

    My concept is that you should pull your Session variables into local variables and then handle them appropriately. Always assume your Session variables could be null and never cast them into a non-nullable type.

    If you need a non-nullable typed variable you can then use TryParse to get that.

    int mySessionInt;
    if (!int.TryParse(mySessionVar, out mySessionInt)){
       // handle the case where your session variable did not parse into the expected type 
       // e.g. mySessionInt = 0;
    }
    

提交回复
热议问题