C# Generic Session Helper

.NET, C#

This simple helper class uses generics to retrieve the correctly typed object from session, removing the need for us to cast in our calling code. It also has methods to set and remove values from the session.

public class SessionUtils
{
    public static T Get<T>(string key)
    {
        var valueFromSession = HttpContext.Current.Session[key];
        if (valueFromSession is T)
        {
            return (T) valueFromSession;
        }
        return default(T);
    }

    public static void Set(string key, object value)
    {
        HttpContext.Current.Session[key] = value;
    }

    public static void Remove(string key)
    {
        HttpContext.Current.Session.Remove(key);
    }
} 

Short but sweet. We call the Get method like so:

var someObject = SessionUtils.Get<SomeObjectType>("sessionKey");

Where 'SomeObjectType' is the type of the object we want to cast to. If the value is not found in session, the default value for that type is returned.

Comments