Mike
Mike

Reputation: 2339

checking if session variable is null returns nullreferenceexception

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?

edit: I also tried

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

Upvotes: 4

Views: 21765

Answers (4)

nmclean
nmclean

Reputation: 7734

edit: I also tried

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

Note that the code in your edit is not checking that Session is not null. If it is null, the expression Session["object"] will still cause the error because this is searching the session instance for the "object" key - so if you think about it logically you are looking for a key in an uninstantiated object, hence the null reference exception. Therefore you need to verify Session has been instantiated before checking if Session["object"] is null:

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

Upvotes: 7

Scott Earle
Scott Earle

Reputation: 680

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

Upvotes: 0

w5l
w5l

Reputation: 5766

Have you checked if Session != null? In your example, both this.Session and this.Session["Key"] can return null, but you checked only the latter. Take into account the option that the Session itself might not exist, so you cannot get data from it, but also cannot write to it.

Upvotes: 0

Amit Tiwari
Amit Tiwari

Reputation: 368

have you check your GetObject() method...it may return null...

Upvotes: 0

Related Questions