The other available helper that is:
ref TValue GetValueRefOrNullRef<TKey, TValue>(Dictionary<TKey, TValue> dictionary, TKey key) where TKey : notnull
Can return a null ref (Unsafe.NullRef<TValue>()) but the value itself is what it is (since TValue is not constrained).
But:
ref TValue? GetValueRefOrAddDefault<TKey, TValue>(Dictionary<TKey, TValue> dictionary, TKey key, out bool exists) where TKey : notnull
Returns a TValue?. (And the reference itself cannot be null.)
There SHOULD be something I'm missing here and if anyone can explain, it'll be great!
I realized that this is required to accomodate reference types. Since the helper adds the default(TValue), the result may obviously be a null, regardless of the TValue parameter nullability.
And this applies also to nullable value types!
(My mind was focused on value types).
This leads to a funny couple of signature where the OrDefault equivalent is not nullable (because it's a OrNullRef) and the OrAdd is nullable...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With