Session Variables as Objects


Or you could think of this as session objects.  Either way the end result is the same.  Everyone uses session variables at some point in their career.  What I am doing is offering what I feel is a better way to deal with session variables.

When I have used session variables in the past I had two main issues; having to remember names and converting them when they were other than string.  Not to mention using Session["SomeName"] was just too much typing without intellisense.  Some people have wrapped their session variables with getters and setters.  That is a nice idea, but still a bit too much work for what I want to do.  After all I want my code to work for me, not just work.  What if we save a class as a session object, and have the class save itself seamlessly as a session variable.  This works great because you access the class thus giving you intellisense, strongly typed variables and you don't need to worry about checking the session since it is all in the class.

To demonstrate this lets create a class that we will use for session information.  Our example class will want to store a name, an age, and a birthday.  First, I will write it as a normal every day class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Simple class to track some
/// user information.
/// </summary>
public class NormalUserInfo
{
    #region Variables
    private string myName;
    private int myAge;
    private DateTime myBirthday;
    #endregion

    #region Constructors
    public NormalUserInfo()
    {
        Name = "";
        Age = 0;
        Birthday = DateTime.Now;
    }
    #endregion//Constructors

    #region Public Methods
    public string Name
    {
        get { return this.myName; }
        set { this.myName = value; }
    }
    public int Age
    {
        get { return this.myAge; }
        set { this.myAge = value; }
    }
    public DateTime Birthday
    {
        get { return this.myBirthday; }
        set { this.myBirthday = value; }
    }
    #endregion//Public Methods

    #region Private Methods
    #endregion//Private Methods
}

Now we have a normal class that we would use in a normal website.  We have private variables, public getters and setters to access the variables, and a constructor.  Lets turn this class into something we can use as a session object.

First we want to decorate it with the Serializable attribute.  While this does not impact the use of this as a session object it allows us to store this class in other ways in the future if we desire it.

/// <summary>
/// Simple class to track some
/// user information.
/// </summary>
[Serializable]
public class NormalUserInfo
{

Next we need to add a couple of private methods for maintenance and a string constant.  One is to save our object to the session; we will call this method often.  The other is to check for our object already existing and initialize our object to the existing one.  The string constant will be our session variable name.
Now our variables region should look like this.

#region Variables
    private const string mySessionName = "_MyUserInfo_";    //Our session name
    private string myName;
    private int myAge;
    private DateTime myBirthday;
#endregion

Our private methods region should look like this.  Notice how we have moved the initialization of default variable values from the constructor to the area where we create our session if it does not already exist.  Note too that if the session does already exist we set our current values equal to those in the session.

#region Private Methods
    private void CheckExisting()
    {
        if (HttpContext.Current.Session[mySessionName] == null)
        {
            //Save this instance to the session
            HttpContext.Current.Session[mySessionName] = this;
            Name = "";
            Age = 0;
            Birthday = DateTime.Now;
        }
        else
        {
            //Initialize our object based on existing session
            NormalUserInfo oInfo = (NormalUserInfo)HttpContext.Current.Session[mySessionName];
            this.Name = oInfo.Name;
            this.Age = oInfo.Age;
            this.Birthday = oInfo.Birthday;
            oInfo = null;
        }
    }
    private void Save()
    {
        //Save our object to the session
        HttpContext.Current.Session[mySessionName] = this;
    }
#endregion//Private Methods

We are almost finished.  The next step is to modify our setters.  After we set the variable to the value, we need to call the Save() method.  Now our public methods should look like this.

#region Public Methods
    public string Name
    {
        get { return this.myName; }
        set { this.myName = value; Save(); }
    }
    public int Age
    {
        get { return this.myAge; }
        set { this.myAge = value; Save(); }
    }
    public DateTime Birthday
    {
        get { return this.myBirthday; }
        set { this.myBirthday = value; Save(); }
    }
#endregion//Public Methods

The last step is checking for an existing session and initializing to it.  We do this in our constructors, or in our case constructor.  We make a call to the CheckExisting() method as shown below.

#region Constructors
    public NormalUserInfo()
    {
        CheckExisting();
    }
#endregion//Constructors

The easiest part is using this class.  In your code behind you should declare a global variable of type NormalUserInfo.  In your page load you should instantiate this variable to a new NormalUserInfo object.

public partial class _Default : System.Web.UI.Page
{
    NormalUserInfo objInfo;
    protected void Page_Load(object sender, EventArgs e)
    {
        objInfo = new NormalUserInfo();
    }
}

Because we declare our objInfo variable globally, and initialize it on the Page_Load event it will be available to us most anywhere else we plan to use it.  I hope this helps you to make better use of session variables when you need to use them.

Up Next
    Ebook Download
    View all
    Learn
    View all