SuperJediMedia Posted November 14, 2014 Share Posted November 14, 2014 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 More sharing options...
0 +virtorio MVC Posted November 14, 2014 MVC Share Posted November 14, 2014 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 More sharing options...
0 SuperJediMedia Posted November 14, 2014 Author Share Posted November 14, 2014 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? Link to comment Share on other sites More sharing options...
0 +virtorio MVC Posted November 14, 2014 MVC Share Posted November 14, 2014 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 More sharing options...
0 notchinese Posted November 14, 2014 Share Posted November 14, 2014 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 More sharing options...
Question
SuperJediMedia
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