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?
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.
See more on this question at Stackoverflow