Checking session if empty or not

Anyname Donotcare picture Anyname Donotcare · Aug 24, 2011 · Viewed 137.2k times · Source

I want to check that session is null or empty i.e. some thing like this:

if(Session["emp_num"] != null)
{

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

Or just

 if(Session["emp_num"] != null)
    {

       // The code
    }

because sometimes when i check only with:

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

I face the following exception:

Null Reference exception

Answer

Roy Goode picture Roy Goode · Aug 24, 2011

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.