Reputation: 79
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.
Upvotes: 2
Views: 4478
Reputation: 10872
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()
.
Upvotes: 0
Reputation: 318
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;
}
Upvotes: 2
Reputation: 79
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...
Upvotes: 0
Reputation: 11339
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.
Upvotes: 3
Reputation: 5689
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;
}
Upvotes: 1