0

In My MVC project, I am using session values like

var empId = Convert.ToInt32(Session["EmpId"].ToString());

I am getting Exception:

"An exception of type 'System.NullReferenceException' occurred in Project.Web.dll but was not handled in user code.

Additional information: Object reference not set to an instance of an object."

1
  • 1
    Have you checked Session["EmpId"] for null? Commented Feb 19, 2015 at 9:58

3 Answers 3

4

This error occurs when you call a method on the null object. In your case the value of Session["EmpId"] is NULL.

Which means you are calling NULL.ToString(), which is invaild hence it throws error.

You can avoid the error using null coaleascing operator or simply check null before performing any opearation on it.

Solution:

if(Session["EmpId"] == null)
 //do something
else
 var empId = Convert.ToInt32(Session["EmpId"].ToString());

Alternatively you can check my blog post on it

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

1 Comment

I have the same issue but my property definition is like this get { if (Session["_exportViewModel1"] == null) Session["_exportViewModel1"] = new BG.Indigo.Controls.Utilities.CountrySurveyReportExportVM(); return (BG.Indigo.Controls.Utilities.CountrySurveyReportExportVM)Session["_exportViewModel1"]; } set { Session["_exportViewModel1"] = value; }
1

Before use first check is it null or not.

var empId = Session["EmapId"] != null ? Convert.ToInt32(Session["EmapId"]) : 0;

Comments

0

You have to check null as shown below :-

var empId = Convert.ToInt32((Session["EmpId"] ?? 0).ToString());

A more efficient way to accomplish your requirement :-

int temp = 0;
var empId = int.TryParse( Convert.ToString( Session["EmpId"] ),out temp );

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.