1.6.7 Boolean Operator Precedence

Overview

C# evaluates ! before &&, and && before ||. Parentheses make a condition’s intended grouping explicit. If a Zoo condition combines sex, the presence of a Baby, and a medical override, changing the grouping can change its result.

bool needsCare = this.Baby != null && this.Sex == "Female"
                 || emergencyOverride;

This expression groups as (this.Baby != null && this.Sex == "Female") || emergencyOverride. The override can make needsCare true even without a Baby. If the intended rule requires a Baby in every case, write this.Baby != null && (this.Sex == "Female" || emergencyOverride) instead.

Compare Two Groupings
The diagram represents the unparenthesized expression: either both the Baby and Female tests succeed, or the override succeeds. It does not represent the parenthesized alternative. Use a case with no Baby and override true to see the difference immed
Compare Two Groupings
  • New
  • Changed
  • Removed

The diagram represents the unparenthesized expression: either both the Baby and Female tests succeed, or the override succeeds. It does not represent the parenthesized alternative. Use a case with no Baby and override true to see the difference immediately.

Trace the Outcome

Add parentheses before mixing operators, then evaluate the expression by hand for Baby null or present, Sex Female or another value, and override false or true. Watch which checks actually run during short-circuit evaluation.

Evaluate the expression in layers: first apply ! to the Boolean immediately after it, next evaluate the && groups, then evaluate ||. Parentheses override that order. Do not rely on a diagram that merely shows three checks in a row; the diagram must preserve the grouping that decides when the entire expression is true.