Checking session if empty or not Checking session if empty or not asp.net asp.net

Checking session if empty or not


Use this if the session variable emp_num will store a string:

 if (!string.IsNullOrEmpty(Session["emp_num"] as string)) {                //The code }

If it doesn't store a string, but some other type, you should just check for null before accessing the value, as in your second example.


if (HttpContext.Current.Session["emp_num"] != null){     // code if session is not null}
  • if at all above fails.


You need to check that Session["emp_num"] is not null before trying to convert it to a string otherwise you will get a null reference exception.

I'd go with your first example - but you could make it slightly more "elegant".

There are a couple of ways, but the ones that springs to mind are:

if (Session["emp_num"] is string){}

or

if (!string.IsNullOrEmpty(Session["emp_num"] as string)){}

This will return null if the variable doesn't exist or isn't a string.