I'm looking at using the ??
operator (null-coalescing operator) in C#. But the documentation at MSDN is limited.
My question: If the left-hand operand is not null, does the right-hand operand ever get evaluated?
The ??= operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null. The left-hand operand of the ??= operator must be a variable, a property, or an indexer element. In C# 7.3 and earlier, the type of the left-hand operand of the ?? operator must be either a reference type or a nullable value type.
The operator stores the value of the right operand expr in the object designated by the left operand lvalue. The left operand must be a modifiable lvalue. The type of an assignment operation is the type of the left operand.
If the left operand is a class type, that type must be complete. The copy assignment operator of the left operand will be called. If the left operand is an object of reference type, the compiler will assign the value of the right operand to the object denoted by the reference.
The call to alert returns undefined (it just shows a message, so there’s no meaningful return). Because of that, && evaluates the left operand (outputs 1 ), and immediately stops, because undefined is a falsy value.
As ever, the C# specification is the best place to go for this sort of thing.
From section 7.13 of the C# 5 specification (emphasis mine):
A null coalescing expression of the form
a ?? b
requiresa
to be of a nullable type or reference type. Ifa
is non-null, the result ofa ?? b
isa
; otherwise, the result isb
. The operation evaluatesb
only ifa
is null.
There are more details around when any conversions are performed, and the exact behaviour, but that's the main point given your question. It's also worth noting that the null-coalescing operator is right-associative, so a ?? b ?? c
is evaluated as a ?? (b ?? c)
... which means it will only evaluate c
if both a
and b
are null.
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