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

}

 

}

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

  • 0

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?

Link to comment
Share on other sites

  • 0

Are any of these objects null: HttpContext.Current.Session ???

 

The 2nd line of the getter is fine, you can safely cast null to any object, it won't complain. That said, you don't need to cast it to a string, its already a string.

Link to comment
Share on other sites

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

    • No registered users viewing this page.