Can't detect whether Session variable exists

Luke picture Luke · Oct 19, 2012 · Viewed 41.3k times · Source

I'm trying to determine if a Session variable exists, but I'm getting the error:

System.NullReferenceException: Object reference not set to an instance of an object.

Code:

    // Check if the "company_path" exists in the Session context
    if (System.Web.HttpContext.Current.Session["company_path"].ToString() != null)
    {
        // Session exists, set it
        company_path = System.Web.HttpContext.Current.Session["company_path"].ToString();
    }
    else
    {
        // Session doesn't exist, set it to the default
        company_path = "/reflex/SMD";
    }

That is because the Session name "company_path" doesn't exist, but I can't detect it!

Answer

Adil picture Adil · Oct 19, 2012

Do not use ToString() if you want to check if Session["company_path"] is null. As if Session["company_path"] is null then Session["company_path"].ToString() will give you exception.

Change

if (System.Web.HttpContext.Current.Session["company_path"].ToString() != null)
{
    company_path = System.Web.HttpContext.Current.Session["company_path"].ToString();
}
else
{
    company_path = "/reflex/SMD";
}

To

if (System.Web.HttpContext.Current.Session["company_path"]!= null)
{
      company_path = System.Web.HttpContext.Current.Session["company_path"].ToString();
}
else
{
      company_path = "/reflex/SMD";
}