1.6.9 Combining Conditions With && and ||

Overview

Use && when both conditions must be true. Use || when either condition can make the whole expression true. In the Zoo, a care check can require an existing Baby and a female Animal, while a display rule could allow either a high temperature or an override.

bool canInspectBaby = this.Baby != null && this.Sex == "Female";
bool showAlert = temperature > 80.0 || manualAlert;

canInspectBaby is true only when both checks succeed. showAlert is true if either temperature is above 80.0 or manualAlert is true. A single & or | is a different C# operator; use the doubled operators for the conditional logic shown here.

Compare the Possible Results
For &&, one false operand makes the result false. For ||, one true operand makes the result true. Parentheses clarify any condition that combines both operators in one expression; operator precedence becomes relevant once they appear together.
Compare the Possible Results
  • New
  • Changed
  • Removed

For &&, one false operand makes the result false. For ||, one true operand makes the result true. Parentheses clarify any condition that combines both operators in one expression; operator precedence becomes relevant once they appear together.

Trace the Outcome

Trace canInspectBaby for a female Animal without a Baby, a male Animal with a Baby, and a female Animal with a Baby. Then trace showAlert when temperature is 75.0 and manualAlert is true.

A truth table can help when the condition is unfamiliar. For a && b, the four input pairs produce false, false, false, and true in order `(false,false)`, `(false,true)`, `(true,false)`, `(true,true)`. For a || b, only the first pair is false. The order in which operands run is a separate short-circuit question.