13

Hi,

To check if the key already exists in cache I shoulde be able to do the following :

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

This does however not work? If I create an instance from the Cache class i will be able to get the object this way :

cache.Get("MyKey") or cache["MyKey"]

But even if I check for null like this :

if(cache["MyKey"] != null)

It will throw an NullRefException?

What am I doing wrong?

Edit1 :

This is how I instansiate the cache

private Cache cache
        {
            get {
                if (_cache == null)
                    _cache = new Cache();
                return _cache; }
        }
MPelletier
  • 16,256
  • 15
  • 86
  • 137
Banshee
  • 15,376
  • 38
  • 128
  • 219
  • How are you instantiating the Cache instance? It isnot your key throwing the NRE, is the cache object itself – Victor Feb 01 '11 at 20:05

2 Answers2

29

Checking for a null value is how to test whether an object for a certain key is in the Cache. Therefore,

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

is correct.

However, you should not instantiate a new Cache object. You may use System.Web.HttpContext.Current.Cache instead. This is the instance of the Cache and lives in the application domain.

From MSDN:

One instance of this class is created per application domain, and it remains valid as long as the application domain remains active. Information about an instance of this class is available through the Cache property of the HttpContext object or the Cache property of the Page object.

marapet
  • 54,856
  • 12
  • 170
  • 184
  • Problem is when a cached object actually is null, and especially where the query to try to get the data again is expensive. – Alex Jul 20 '18 at 13:11
0

You should be checking if the cache is not Null & post that check if the key exists or not (by using .Contains method).

if (myCache != null && myCache.Contains("keyName") && myCache.Get("keyName") != null)
        {
            myDS = (DataSet)myCache.Get("keyName");
        }
Biki
  • 2,518
  • 8
  • 39
  • 53