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.
For example, when evaluating a logical AND (&&), the second operand will not be evaluated if the first operand is false.
Short-circuiting is useful in cases when evaluating later operands would throw an exception.
For example, in the code below, if the variable d is null, the first operand is false, which means that the entire expression is evaluated as false. d.CanBark, which would throw an exception, is not evaluated.
1
2
3
| // d is of type Dogif ((d != null) && (d.CanBark)) d.Bark(); |
Without the ability to short-circuit the expression, we’d have to do the check in two different if statements:
1
2
3
| if (d != null) if (d.CanBark) d.Bark(); |

