MemoryCache generic TryGetValue throws InvalidCastException when trying to get value
tstanitz opened this issue · 6 comments
Hello,
I have found that InvalidCastException coming from the generic TryGetValue extension method when the type of the value related to the key is not compatible with the provided generic type.
To reproduce:
- Add a value to the cache for some key
- Call the TryGetValue generic method with a key and a non-compatible out parameter
- InvalidCastException is thrown
It should not throw any exception, but return false and set the out parameter to default.
The exception comes from the explicit casting:
https://github.com/aspnet/Caching/blob/23a89b78fedea611d74e3a754bc4843115013ae1/src/Microsoft.Extensions.Caching.Abstractions/MemoryCacheExtensions.cs
Thanks
Do you really use different object types in the same cache key? It seems like that would get very confusing.
I agree with you that it is and edge case, but I think it is not a good idea to throw exception from this method, therefore I have reported it.
I think we should still follow the convention of other APIs for Try* where if it's not successful, it should return false instead of throwing.
I agree that when it doesn't throw InvalidCastException, but returns false then it is not able to differenciate the two cases when the key is not existing in the cache or it exists but not able to cast.
As I see the ConcurrentDictionary TryGetValue(TKey key, out TValue value) and MemoryCache TryGetValue(object key, out object value) also throws exception (ArgumentNullException when key is null) but at least it is documented.
Could you please decide to change it to not throw exception just return false or update the document to mention the InvalidCastException or leave it as it is
Thanks in advance
Hello,
Can I create a pull request with the suggested improvement?
Thanks
Tamas