Karthikeyan P
Karthikeyan P

Reputation: 1267

"System.NullReferenceException" for Using Session in MVC

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

Upvotes: 0

Views: 5095

Answers (3)

Karthik Chintala
Karthik Chintala

Reputation: 5545

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

Upvotes: 4

Ajay
Ajay

Reputation: 6590

Before use first check is it null or not.

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

Upvotes: 1

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18883

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 );

Upvotes: 0

Related Questions