---
title: "Checking if session variable is null returns nullreferenceexception"  
description: "Checking if session variable is null returns nullreferenceexception"  
author: "Anonymous User"  
published: 2014-01-29  
updated: 2014-01-29  
canonical: https://www.mindstick.com/forum/1913/checking-if-session-variable-is-null-returns-nullreferenceexception  
category: "c#"  
tags: ["c#"]  
reading_time: 1 minute  

---

# Checking if session variable is null returns nullreferenceexception

I have a List of [objects](https://www.mindstick.com/forum/145447/what-are-objects) stored in a [session variable](https://www.mindstick.com/forum/12804/how-to-set-a-asp-dropdownlist-selectedvalue-to-a-session-variable). But when I check to make sure the session variable is [not null](https://www.mindstick.com/interview/1933/what-is-not-null-constraint), it gives me a [NullReferenceException](https://www.mindstick.com/forum/159752/what-is-a-nullreferenceexception-and-how-can-you-prevent-it-in-your-dot-net-core-application): Object [reference](https://www.mindstick.com/forum/774/reference-what-does-this-error-mean-in-php) not set to an [instance of an object](https://www.mindstick.com/forum/376/system-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](https://www.mindstick.com/forum/12878/how-to-check-if-an-asp-dot-net-file-upload-control-has-a-file-in-jquery) the Session is null?

I also tried

if(Session["object"] != null)

## Replies

### Reply by Pravesh Singh

Hi Tanuj,\
Try checking if (![Session](https://www.mindstick.com/articles/12042/session-in-c-sharp).ContainsKey("object")) after checking if (Session != null). If those checks both pass, then Session["object"] should be fine.


---

Original Source: https://www.mindstick.com/forum/1913/checking-if-session-variable-is-null-returns-nullreferenceexception

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
