#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();
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #985 – Why It’s Useful for Conditional Operators to Short-Circuit Evaluation

  1. Pingback: Dew Drop – December 2, 2013 (#1674) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: