简体   繁体   中英

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.

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"];

You need to check the object first, try:

var isChaffeurUsed = false;

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

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"];

最有可能的是,您在Session没有任何名称为"IsChaffeurUsed"

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"];

由于以下原因存在TryParse()方法:

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

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...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM