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
requires a
to be of a nullable type or reference type. If a
is non-null, the result of a ?? b
is a
; otherwise, the result is b
. The operation evaluates b
only if a
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…