• 0

Object reference not set to an instance of an object.


Question

How to fix this with an Object reference not set to an instance of an object. error?

 

public static string UserName

{

 

get

{

String username= HttpContext.Current.Session["UserName"].ToString();

return username==null ? String.Empty : username as String;

}

 

 

set

 

{

HttpContext.Current.Session["UserName"] = value;

}

 

}

 

4 answers to this question

Recommended Posts

  • 0

At a guess, either the session object isn't ready at the point you're trying to use it, or there is no variable "UserName" in Session and as such you're calling .ToString() on a null object.

 

You could try:

get
{
  object username= HttpContext.Current.Session["UserName"];
  return username==null ? String.Empty : username.ToString();
}

 

Step thought your code and see where the error is happening, then you'll know the reason it's happening.

  • 0
  On 14/11/2014 at 04:27, SuperJediMedia said:

Any suggestions on how to fix this? Sorry, I am newbie :(

 

Can I put an if statement in this property or it's not necessary?

Did you try the change I suggested above?

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.