1.6.10 Short-Circuit Evaluation

Overview

&& and || can finish evaluating as soon as the result is known. With &&, a false left side means the right side is not needed. With ||, a true left side means the right side is not needed. This is called short-circuit evaluation.

if (this.Baby != null && this.Baby.Weight > 0)
{
    // Inspect the Baby's positive weight.
}

When Baby is null, the left side is false. C# skips this.Baby.Weight > 0, avoiding an attempt to read Weight through a null reference. When Baby exists, the second test runs. Put the guard before the expression that requires the guarded object.

Observe the Skipped Operand
An || expression behaves differently: if its left side is already true, C# skips the right side. Short-circuiting does not change Boolean logic; it changes which expressions need to run. This matters when a later expression reads an object field or c
Observe the Skipped Operand
  • New
  • Changed
  • Removed

An || expression behaves differently: if its left side is already true, C# skips the right side. Short-circuiting does not change Boolean logic; it changes which expressions need to run. This matters when a later expression reads an object field or calls a method.

Trace the Outcome

Pause at the if with Baby null, then with a Baby whose Weight is positive. Predict whether the second operand will be evaluated each time. Never reverse the operands in this example: accessing this.Baby.Weight first would be unsafe when Baby is null.

The left-to-right order is part of this safety pattern. this.Baby != null && this.Baby.Weight > 0 checks the reference before reading Weight. this.Baby.Weight > 0 && this.Baby != null tries to read Weight first and can fail. For ||, put an inexpensive or sufficient test first when you intentionally want to skip the second operand after a true result.