0

I have created a class with name Examination, in this class I have a method with name Get Question(), in take exam when i am creating object of Examination and Run Application it gives following error.

NullReferenceException: Object reference not set to an instance of an object.

Source Error: 


Line 18:         Examination e = (Examination)Session["questions"];
Line 19:         // display data
Line 20:         lblSubject.Text = e.sname;
Line 21:         lblQno.Text = e.curpos + 1 + "/" + e.SIZE;
Line 22:         lblCtime.Text = DateTime.Now.ToString();
6
  • Is the exception thrown at line 20? Commented Dec 10, 2013 at 12:55
  • @JennyO'Reilly yes on line 20 Commented Dec 10, 2013 at 12:58
  • Seems like e is null, first check whether Session["questions"] contains data and if it is possible to cast it to Examination. Commented Dec 10, 2013 at 13:02
  • You know that line 18 does not create an object but reads it from the session, right? Commented Dec 10, 2013 at 13:05
  • @JennyO'Reilly i am creating object of Examination But Give red color ErrorLine without discription Examination e=new Examination(); Commented Dec 10, 2013 at 13:16

1 Answer 1

3

Most probably Session["questions"] does not contain a value, and returns null. It is perfectly valid to cast null to a reference type, but the exception occurs where you try to access properties of it.

You should test if it's null, for instance:

Examination e = (Examination)Session["questions"];
if (e == null)
{
    lblSubject.Text = "Your session has expired";
}

(If I'm wrong, and e actually contains a reference to an Examination object, then it's lblSubject that's null)

Sign up to request clarification or add additional context in comments.

3 Comments

if e null then what to do
When your Session (20 minutes per default iirc) times out, e is gong to be null. In this case, you need to reinitalize the session. There are event handlers for this: msdn.microsoft.com/en-us/library/ms178583.aspx
As mentioned Session["questions"] is probably null. Its always a good practice to check for null before using any object specially if its returned from a different class/source (even if it can never be null). What if the implementation of the other class/source changes in future? Its just safe to check.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.