I would like to store an integer value in the application cache.
The GetOrSet
method should always return an int, and never be null. If there is no cached value, then the getDataCallback
function will provide the integer.
But I need the cache check to return a nullable int in order to distinguish no value
from a 0
integer value.
I am looking for any faults in the code below, or possible improvements.
It probably looks very simple to others, but I find working with nullable ints quite confusing.
public int GetOrSet(string cacheKey, Func<int> getDataCallback)
{
int? data = (int?)HttpContext.Current.Application[cacheKey]; // this should return null if there is no value stored in the cache
if (! data.HasValue)
{
int intData = getDataCallback();
HttpContext.Current.Application[cacheKey] = intData;
return intData;
}
else
{
return data.Value;
}
}
Update
Big thanks to both @Nkosi and @Flater for their help.
I marked @Flater's answer as correct because I had to chose one only. But I really hated having to do this as both answers were equally helpful and I used both their suggestions in the end. I would encourage anybody reading this to check them both out.
HttpContext
would make it not unit testable asHttpContext.Current
isnull
outside of IIS. consider encapsulating that code behind an abstraction. other than that you logic is sound but can also benefit from some defensive coding (null check on the callback) \$\endgroup\$HttpContext.Current
or could I just do it for theApplication
bit? \$\endgroup\$