CHECKING IF SESSION VARIABLE IS NULL RETURNS NULLREFERENCEEXCEPTION

Total Post:134

Points:940
C# 
C#
 2518  View(s)
Ratings:
Rate this:

I have a List of objects stored in a session variable. But when I check to make sure the session variable is not null, it gives me a NullReferenceException: Object reference not set to an instance of an object.

if(Session["object"] == null)  //error occurs here
{
     Session["object"] = GetObject();
     return Session["object"] as List<object>;
}
else
{
    return Session["object"] as List<object>;
}

How can I check if the Session is null?

I also tried

if(Session["object"] != null)

  1. Post:412

    Points:2888
    Re: Checking if session variable is null returns nullreferenceexception

    Hi Tanuj,


    Try checking if (!Session.ContainsKey("object")) after checking if (Session != null). If those checks both pass, then Session["object"] should be fine.

      Modified On Apr-04-2018 02:21:56 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!