In this code snippet i simply put null in MemoryCache and then check if this key exists:
MemoryCache _cache = new(new MemoryCacheOptions());
_cache.Set<string>(cacheKey, null);
bool isInCache = _cache.TryGetValue(cacheKey, out string nothing);
isInCache
is false in this case. Is this behavior expected?
I use .NET Core 2.2 Console app.
Based on the source code for TryGetValue()
it will return false
if null is returned when it checks type if (result is TItem item)
. However, the .Count
property would return 1. (thanks to @jgoday comment for these details).
An alternative is to have a 'null value' (e.g. Guid.NewGuid()
) that you can use to represent a null value, this way something is entered into the cache so you can verify whether it has ever been added.
public class MyCache
{
private MemoryCache _cache = new MemoryCache(new MemoryCacheOptions());
private string nullValue = Guid.NewGuid().ToString();
public void Set(string cacheKey, string toSet)
=> _cache.Set<string>(cacheKey, toSet == null ? nullValue : toSet);
public string Get(string cacheKey)
{
var isInCache = _cache.TryGetValue(cacheKey, out string cachedVal);
if (!isInCache) return null;
return cachedVal == nullValue ? null : cachedVal;
}
}