Yes, that is legal (but the question in the title is not, see below for details).
Though, it may be wise to check that the type in the cache is what you're expecting rather than having to do this check twice, such as:
//in English, the following line of code might read:
// if the item known in the cache by the specified key is in
// in fact of type MyExpectedReferenceType, then give me it
// as such otherwise, give me a null reference instead...
var myCachedInstance = Cache[key] as MyExpectedReferenceType;
if (myCachedInstance == null)
{
//we retrieved a reference to an instance of an MyExpectedReferenceType
}
else
{
//oh, no - we didn't!
}
On re-reading your question though, and thinking about your program not working properly, I'm tempted to say you have bigger issues than this; how is your program not working correctly? The Cache
instance itself will never be null
while accessible - it is a read-only field of Page
. However, your expected cached value could be null
and, if this is the problem, you should be receiving a NullReferenceException
- is that the case?
UPDATE:
To address your comment, check out the comments I added to the code.