#91 – Conditional Operators Can Short-Circuit Evaluation

C# won’t necessarily evaluate every sub-expression in a larger expression.  If knowing the value of the first operand is sufficient for knowing the value of the entire expression, the larger expression is said to be short-circuited.

When evaluating a logical AND (&&), the second operand will not be evaluated if the first operand is false.  The entire expression is false.

bool b1 = false && expr;   // Result is false; expr never evaluated

When evaluating a logical OR (||), the second operand will not be evaluated if the first operand is true.  The entire expression is true.

bool b1 = true || expr;   // Result is true; expr never evaluated

Advertisements