Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Cannot check Session exists?

I get an error when I do the following:

if(Session["value"] != null)
{
   // code
}

The error i get is this:

Object reference not set to an instance of an object.

Why is this? I always check my session this way? I am using the MVC Framework, does this has something to do with it?

EDIT:

The code is in the constructor of a Controller:

public class MyController : ControllerBase
{
    private int mVar;

    public MyController()
    {
        if (Session["value"] != null)
        {
            mVar= (int)Session["value"];
        }
    }
}
like image 352
Martijn Avatar asked Apr 17 '09 09:04

Martijn


1 Answers

The [] is an indexer, it acts like a method on the class.

In this case, Session is null and you cannot perform the indexing on it.

Do this:

if(Session != null && Session["value"] != null)
{
   // code
}
like image 156
Nick Whaley Avatar answered Sep 19 '22 05:09

Nick Whaley