#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


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #91 – Conditional Operators Can Short-Circuit Evaluation

  1. Pingback: #985 – Why It’s Useful for Conditional Operators to Short-Circuit Evaluation | 2,000 Things You Should Know About C#

  2. kai zhou says:

    “short-circuited”.
    Thank you Sean.

Leave a comment