Correct using of ASP.NET Cache.NET Tip of The Day.org

Posted on January 30, 2008 by (author unknown).
Categories: Contributors.

Often in ASP.NET application we see a code which looks like this one:

    if (Cache["SomeData"] != null)

    {

        string name = ((SomeClass)Cache["SomeData"]).Name;

        //.....

    }

This code is not safe enough and the second statement can generate a NullReferenceException sometimes. There is no guaranttee that a cached object will stay in the cache between two calls. After the first call it can be deleted either by garbage collector or by another thread to refresh cached data.

So to overcome this problem rewrite the code using as operator:

    SomeClass someClass = Cache["SomeData"] as SomeClass;

    if (someClass != null)

    {

        string name = someClass.Name;

        //.....

    }

via Dmytro Shteflyuk