Those who prefer reading this site through RSS now can also subscribe for updates to .NET Tips & Tricks Community.
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
1/30/2008