Search code examples
c#asp.netsessionnullreferenceexceptiontostring

Checking session if empty or not


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


Solution

  • 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.