Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

No More Session Variable Misspellings

0.00/5 (No votes)
6 May 2019 1  
This is an alternative for No More Session Variable Misspellings

Introduction

I started doing some MVC stuff, and came up with another way that doesn't involve any outward-facing casting to the object's type, AND preserves the strong typing that we all know and love in real programming languages:

Using the Code

I set up a static class called SessionVars that contains a property for each variable.

public static class SessionVars
{
    // provided to simplify typing in the actual session var properties
    public static HttpSessionState Session 
    {
        get
        {
            return System.Web.HttpContext.Current.Session;
        }
    }
    
    public static string MyStringVar
    {
        get
        {
            string value = string.Empty;
            if (SessionVars.Session != null)
            {
                object obj = SessionVars.Session["myStringVar"];
                value = (obj == null) ? default(string) : (string)obj;
            }
        }
        set
        {
            SessionVars.Session["myStringVar"] = value;
        }
    }
}

Keep in mind that this doesn't remove the need for casting, it simply abstracts it away so you can do the following in your code:

string myValue = SessionVars.MyStringVar;

Which is a lot cleaner than doing it this way:

string myValue = (string)(System.Web.HttpContext.Current.Session["myStringVar"]);

You also don't have to worry about how the variable key was spelled, because that's all handled in the property that you defined.

One final note - .NET Core handles the session state quite differently, and while this code won't work in .NET Core, all you have to do is change the property that returns the session state to do it the Core way, and all of the other properties should theoretically work without changes.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here