King_Fisher
King_Fisher

Reputation: 1203

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 ?

Upvotes: 2

Views: 25352

Answers (1)

Maximilian Gerhardt
Maximilian Gerhardt

Reputation: 5353

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

Upvotes: 4

Related Questions