#985 – Why It’s Useful for Conditional Operators to 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.

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.

            // d is of type Dog
            if ((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:

            if (d != null)
                if (d.CanBark)
                    d.Bark();
Advertisement