Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does CollectionMarshal.GetValueRefOrAddDefault returns a ref nullable TValue?

Tags:

c#

dictionary

ref

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!

like image 848
Spi Avatar asked Dec 11 '25 04:12

Spi


1 Answers

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...

like image 67
Spi Avatar answered Dec 13 '25 21:12

Spi