Wrap Your NameValue Variables

Share this article

ASP.NET gives a developer a lot of loosely typed key-value collections in which to stash stash variables, depending upon persistence needs. The short list includes ViewState, Session, Application and HttpContext.Items. These collections can come in very handy when one needs to keep an object around outside of a single request or shuttle things between different bits of the http pipeline. But it comes at a price—these collections are loosely typed, just returning Objects. Moreover, there is no compile-time checking to ensure that you are requesting the right key in the right place. Errors can lead to crashes at best, and interesting data corruption at worst.

But those issues can easily be avoided with a little discipline up front. You see, rather than calling these variables directly, it is very possible to wrap them in an appropriately-scoped property and have that manage access to the underlying data. For the examples we are going to use the Session, but the semantics will remain the same with just about any of the above collections.

So, let’s say we have a little web store. And this web store has a shopping cart. And we are going to stash this Shopping Cart object in the session. Now, one could many instances of code like this:


ShoppingCart sc=(ShoppingCart)Session[“ShoppingCart”];
If (sc==null)
{
      sc=new ShoppingCart();
}
//do stuff with ShoppingCart.

Or, one a base page class somewhere, you could define something like:


protected ShoppingCart Cart
{
    get
    {
        if (Session["ShoppingCart"] == null)
        {
            Session["ShoppingCart"] = new ShoppingCart();
        }
        return (ShoppingCart)Session["ShoppingCart"];
    }
}

The advantages of this approach are that the calling code never even needs to worry about where/how the shopping cart is stored, or if it can be null, or how to cast it out of the underlying store. Furthermore, if, at a future date, you decide that you are better off storing this cart in, say, the viewstate, the change is very, very easy because it only needs to be updated in one place.

Enjoy and don’t be afraid to kick it on DotNetKicks.com.

Wyatt BarnettWyatt Barnett
View Author
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week