#1,201 – Writing Conditional Logical Operators as Conditionals

The conditional logical operators (&&, ||) can short-circuit evaluation, based on the value of the left side of the expression.

  • For &&, evaluation short-circuits if left-side is false (result is false)
  • For ||, evaluation short-circuits if left-side is true (result is true)

You can also think of the conditional logical operators as being equivalent to the ternary conditional operator.

            bool leftSide = true;
            bool rightSide = false;

            // Short-circuits (right side not evaluated)
            bool bResult = leftSide || rightSide;

            // || Equivalent to
            bResult = leftSide ? true : rightSide;

            // Short-circuits if left side is false
            bResult = leftSide && rightSide;

            // && Equivalent to
            bResult = leftSide ? rightSide : false;

#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