State Street Gang
.NET, straight up

Safest Way to Get the Cache Object

May 20, 2008 11:23 by will

This is one of those "I keep forgetting this so I'd better put it in a blog post" blog posts. 

We've all seen this:

object bar = HttpContext.Current.Cache["foo"];

And we've all had null reference exceptions thrown because of it.  Usually, we duct tape it back together with the pitiful:

if (HttpContext.Current == null)
    throw new InvalidOperationException
        ("Lol you're screwed");
object bar = HttpContext.Current.Cache["foo"];

Or we add on more logic to return a non-offensive result that is incorrect, but since there is no current context (usually happens when the web server is recycling), what do we care? 

There is a better way.  One where you will always get the cache, and it will never be null:

object bar = HttpRuntime.Cache["foo"];

No matter what's going on, the HttpRuntime's cache property will never be null.  And it's the same object as that in HttpContext.Current.  If you don't believe me, just slap the following in any ASP.NET page:

Assert.IsTrue(object.Equals(HttpContext.Current.Cache,HttpRuntime.Cache);

Tags:
Categories: ASP.NET | Tips
Actions: E-mail | Permalink | Comments (1) | Comment RSSRSS comment feed

Related posts

Comments

May 26. 2008 03:46

Matthijs

You can also use Reflector, it shows the code for HttpContext.Current.Cache:

public Cache Cache
{
get
{
return HttpRuntime.Cache;
}
}

Matthijs

Comments are closed