'Generic cache method - when T is an int, how can I differentiate between null and zero?
I am trying to implement a caching solution.
When caching an int value I want to distinguish between 0 and the non-existance of a cache (null). Therefore I have used var cachedData = (int?)_cacheImplementation.GetItem(cacheKey).
When caching a T value I don't think that I can use this approach because I can't add the nullable operator onto T.
The result is that I have to use a separate method for int cache retrieval and T cache retreival (as below), but I would like to unify them into a single method if possible.
Ideally I would like just the T version and to be able to use int as the type for T. But differentiating 0 from null is tripping me up.
public IApplicationCachingServiceResult<int> GetCache(
string cacheKey
, Func<int> valueFactory
)
{
var cachedData = (int?)_cacheImplementation.GetItem(cacheKey);
return cachedData.HasValue
? new ApplicationCachingServiceResult<int>(cachedData.Value)
: new ApplicationCachingServiceResult<int>(
CreateCacheItem(cacheKey, valueFactory)
);
}
public IApplicationCachingServiceResult<T> GetCache<T>(
string cacheKey
, Func<T> valueFactory
)
{
return _cacheImplementation.GetItem(cacheKey) is T cachedData
? new ApplicationCachingServiceResult<T>(cachedData)
: new ApplicationCachingServiceResult<T>(
CreateCacheItem(cacheKey, valueFactory)
);
}
_cacheImplementation.GetItem is implemented as follows:
public object GetItem(string cacheKey)
{
if (_memoryCache.TryGetValue(cacheKey, out var cachedValue))
{
return cachedValue;
}
else
{
return null;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
