1

Suppose i have 2 pages 'A' and 'B'. i set a session variable in 'A', that is checked in page_load function in page 'B' using:

 if (!string.IsNullOrEmpty(Session["x"].ToString()))
 {
 }

and the appropriate actions are performed based on the value of that session variable but if I open page 'B' first , it gives the error:

 Object reference not set to an instance of an object.

How do i set the instance of this object beforehand itself?

2 Answers 2

1

You are getting exception before the IsNullOrEmpty comes in to action and parameter passed to IsNullOrEmpty is evaluated. You will get the exception By calling ToString() on Session["x"] if Session["x"] is null. So you will get exception before the call to IsNullOrEmpty is made.

Change

if (!string.IsNullOrEmpty(Session["x"].ToString())) {} 

To

if(Session["x"] != null && Session["x"].ToString() != string.Empty) {} 
Sign up to request clarification or add additional context in comments.

Comments

1

You are using Session["x"].ToString() when SessionX is null that's why you are getting null exception So you should check that Session["x"] should not be null

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

Comments

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.