Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the right-hand side of C#'s null coalescing operator (??) lazily evaluated? [duplicate]

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.

like image 584
stakx - no longer contributing Avatar asked Aug 30 '25 16:08

stakx - no longer contributing


1 Answers

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);
like image 64
stakx - no longer contributing Avatar answered Sep 09 '25 15:09

stakx - no longer contributing