Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking if session variable is null returns nullreferenceexception

Tags:

c#

session

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)
like image 936
Mike Avatar asked Mar 20 '23 18:03

Mike


1 Answers

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;
}
like image 155
nmclean Avatar answered Apr 06 '23 19:04

nmclean