C#C
C#3y ago
Ruttie

✅ `??=` and `??`

This question may not fit here because it is not a question about C# but more about why it is implemented in such a way, but I'll ask anyways:

Why is
item ??= item2
implemented as
            if ((object)item == null)
            {
                item = item2;
            }
instead of
            if (item == null)
            {
                item = item2;
            }
?
The cast makes it so if the
==
operator is changed by the class, it will not use said operator, instead using the default
==
operator of
object
.
This makes it so that in unity for example, where the
==
operator is changed by all unity objects, the
??=
operator cannot be used.

My other question is, does the
??
operator also cast to
object
before null checking, or does it use something else completely, like pattern matching? I've used https://sharplab.io to see the lowering of
??
, but it doesn't appear to be lowered.
Was this page helpful?