I have an object MyObject and I’m storing that in the session.
I write this:
MyObject TheObject = HttpContext.Current.Session["TheObjInSession"] as MyObject;
I’m getting error Object reference not set to an instance of an object Why? I thought that if you use as to cast and the cast produces an error then it just returns null and execution continues. How should I rewrite this line?
Thanks for your suggestions.
PS: The error is produced because I removed the enable session line [WebMethod(EnableSession = true)] I’ll put the line back in but I want to make sure there are no exceptions in case anything goes wrong.
Chances are the
Sessionis triggering it (it either doesn’t exist or hasn’t been established). This is common in handlers if you haven’t marked the class to manage sessions.Yes, you’re right,
aswill attempt a cast or result in anull, but that’s only assuming you’re left-hand object is valid and has a value to attempt a cast on.To explain it a bit more in depth:
Which essentially makes referencing a key off the
Sessionelement impossible ifSessionitself doesn’t exist.