The question's title says it all. In a C# expression a ?? b
, is b
always evaluated, or only when a
evaluates to null
?
I am curious about this because it might matter in cases when evaluating the right-hand-side expression might have side effects, or when its evaluation might be computationally expensive.
The right-hand side of ??
is lazily evaluated; that is, it gets evaluated only when the expression on the left-hand side has evaluated to null
. This can be easily tested:
bool rhsExpressionWasEvaluated = false;
bool _ = (bool?)true ?? (rhsExpressionWasEvaluated = true);
Debug.Assert(!rhsExpressionWasEvaluated);
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