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)
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With