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);