Stuck
Stuck

Reputation: 259

Object reference not set to an instance of an object error message

What is wrong with my code? I recently posted a question about Calculation in code behind and I tried Vinoth's answer but it gives me an error at this line:

bool isChaffeurUsed = (bool)Session["IsChaffeurUsed"];

error message is: Object reference not set to an instance of an object.

Please tell me what should i do. Many thanks and have a nice day.

Upvotes: 0

Views: 5297

Answers (7)

SPFiredrake
SPFiredrake

Reputation: 3892

One thing about looking at session variables is that there's a possibility the variable will be gone after the initial read (this has happened to me on a few occasions). This is usually the pattern I use when dealing with looking at session/cache variables in an ASP app:

object o = null;
if((o = Session["IsChaffeurUsed"]) != null)
{
    // Do something with o: bool.Parse, (bool), etc...
}

Upvotes: 0

Kyle B.
Kyle B.

Reputation: 5787

TryParse() methods exist for this reason:

bool.TryParse(Session["IsChaffeurUsed"], out isChaffeurUsed)

Upvotes: 0

Matt Varblow
Matt Varblow

Reputation: 7881

You would get that exception if Session was null or if IsChaffeurUsed was not found in Session. Session is probably not null, so the problem is likely that IsChaffeurUsed is not found.

You need to decide what to do if the IsChaffeurUsed was not set. For example, you could assume it's false:

bool isChaffeurUsed = Session["IsChaffeurUsed"] == null ? false 
     : (bool)Session["IsChaffeurUsed"];

Upvotes: 1

Dan Puzey
Dan Puzey

Reputation: 34200

Most likely, you don't have anything in Session with the name "IsChaffeurUsed".

Upvotes: 1

Justin Niessner
Justin Niessner

Reputation: 245399

The error is trying to tell you that Session["IsChaffeurUsed"] doesn't exist.

If you know a default value, you could change the statement to read:

bool isChaffeurUsed = (bool)(Session["IsChaffeurUsed"] ?? false)

Or, if you want to allow null values (which would indicate that the value wasn't set specifically to any value), you could use a nullable type:

bool? isChaffeurUsed = (bool?)Session["IsChaffeurUsed"];

Upvotes: 3

Shai
Shai

Reputation: 25619

Session["IsChaffeurUsed"]

Is not defined - you haven't set any session variable with the key IsChaffeurUsed

You need to check if it's set first,

bool isChaffeurUsed;

if(Session["IsChaffeurUsed"] != null)
    isChaffeurUsed = (bool)Session["IsChaffeurUsed"];

Upvotes: 4

Jupaol
Jupaol

Reputation: 21365

You need to check the object first, try:

var isChaffeurUsed = false;

if (Session["IsChaffeurUsed"] != null)
{
    isChaffeurUsed  = bool.Parse(Session["isChaffeurUsed"].ToString());
}

Upvotes: 3

Related Questions