2

In the below snippet, I am trying to assign the cache value if the cache value does not already exist. I get an Object_reference_not_set_to_an_instance_of_an_object error when running the following. What am I missing?

if (string.IsNullOrEmpty(HttpContext.Current.Cache[Key].ToString()))
                HttpContext.Current.Cache[Key] = data;

I looked around on SO but couldnt find something similar. Maybe I am just not wording my problem correctly.

yoyo
  • 79
  • 3
  • 11

5 Answers5

3

HttpContext.Current could be null. HttpContext.Current.Cache[Key] could be null.

If either of those are null, it would result in the error you are getting.

Nathan A
  • 11,059
  • 4
  • 47
  • 63
2

You should check for null on HttpContext.Current and on HttpContext.Current.Cache[Key], both of which could be null. Here's a possible solution, as long as you're okay with not setting the cache key if HttpContext.Current is null.

if (HttpContext.Current != null &&
    (HttpContext.Current.Cache[Key] == null || string.IsNullOrEmpty(HttpContext.Current.Cache[Key].ToString()))
{
     HttpContext.Current.Cache[Key] = data;
}
zmarks22
  • 318
  • 1
  • 9
1

You are getting the NullReferenceException because you are trying to call ToString() on a null instance.

You have to check if HttpContext.Current.Cache[Key] is null before calling ToString()

if (HttpContext.Current.Cache[Key] == null)
{
   HttpContext.Current.Cache[Key] = data;
}
Cam Bruce
  • 5,632
  • 19
  • 34
0

I just changed the 'get value, convert to string, compare' logic to just get the value and see if it's null right up front. Silly me.

if (HttpContext.Current.Cache[Key] == null)
       HttpContext.Current.Cache[Key] = data;

The "Object_reference_not_set_to_an_instance_of_an_object error" is actually essentially the 'null' value I was looking for...

yoyo
  • 79
  • 3
  • 11
0

If they key isn't present, then this would return null:

HttpContext.Current.Cache[Key]

You're then blindly calling ToString() on the value from the cache, causing the exception.

You need to assign the value from the cache to a temporary variable and test it for null before calling ToString().

Martin Costello
  • 9,672
  • 5
  • 60
  • 72