The extension method GetOrCreateAsync
for IMemoryCache
:
public static async Task<TItem?> GetOrCreateAsync<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, Task<TItem>> factory)
{
if (!cache.TryGetValue(key, out object? result))
{
using ICacheEntry entry = cache.CreateEntry(key);
result = await factory(entry).ConfigureAwait(false);
entry.Value = result;
}
return (TItem?)result;
}
Why do they returns TItem?
instead of just TItem
? Assuming my factory
method never returns null, is it safe to assume it would never be null
and just ignore it with null-forgiving operator !
?
public async Task<Foo> GetFooAsync()
=> (await cache.GetOrCreateAsync("Foo", async _ => new Foo()))!
?
after the type. This symbolises a nullable variable. The reason it probably returns like a nullable is becauseresult
could be null, its not safe to assume that it won't be null. I suggest implementing a null check before using the return data. – CasseyTItem
instead ofTItem?
. But you are right that I want to know why they don't do that, there may be a situation that somehow it could benull
. However that's extra logic for gettingFoo
incase it's null (basically almost copy the factory method) – CashierGetOrCreate()
is only a part of the whole interface. Maybe other methods allow writing cache values that arenull
? – Dreadfulnull
value) I can safely ignore it I guess. – Cashier