King_Fisher King_Fisher - 2 months ago 67
C# Question

Set and get session values in HttpContext.Current.Session in C#

I have static class called CommoonHelper.

public static class CommonHelper
{

public static SessionObjects sessionObjects
{
get
{

if ((HttpContext.Current.Session["sessionObjects"] == null))
{

return null;
}
else
{
return HttpContext.Current.Session["sessionObjects"] as SessionObjects;
}
}
set {
HttpContext.Current.Session["sessionObjects"] = value;
}
}

}


In SessionObjects Class, I have defined properties for get /set like below.

public class SessionObjects
{
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string DisplayName
{
get
{
return FirstName + "" + LastName;
}
}
}


When i try to assign an value like below.

CommonHelper.sessionObjects.LastName = "test";


Its throwing the below exception.

System.NullReferenceException: Object reference not set to an instance of an object.


How do i fix this ?

Answer

Try creating a new instance of the SessionObjects class when the SessionObjects object of the current instance is null.

 public static  class CommonHelper
    {    
        public static SessionObjects sessionObjects
        {
            get
            {
                if ((HttpContext.Current.Session["sessionObjects"] == null))
                    HttpContext.Current.Session.Add("sessionObjects", new SessionObjects()); 
                return HttpContext.Current.Session["sessionObjects"] as SessionObjects;
            }
            set { HttpContext.Current.Session["sessionObjects"] = value; }
        }
    }
Comments