Short-circuiting Operators

Download c# eBook

Example

By definition, the short-circuiting boolean operators will only evaluate the second operand if the first operand can not determine the overall result of the expression.

It means that, if you are using && operator as firstCondition && secondCondition it will evaluate secondCondition only when firstCondition is true and ofcource the overall result will be true only if both of firstOperand and secondOperand are evaluated to true. This is useful in many scenarios, for example imagine that you want to check whereas your list has more than three elements but you also have to check if list has been initialized to not run into NullReferenceException. You can achieve this as below:

bool hasMoreThanThreeElements = myList != null && mList.Count > 3;

mList.Count > 3 will not be checked untill myList != null is met.

Logical AND

&& is the short-circuiting counterpart of the standard boolean AND (&) operator.

var x = true;
var y = false;

x && x // Returns true.
x && y // Returns false (y is evaluated).
y && x // Returns false (x is not evaluated).
y && y // Returns false (right y is not evaluated).

Logical OR

|| is the short-circuiting counterpart of the standard boolean OR (|) operator.

var x = true;
var y = false;

x || x // Returns true (right x is not evaluated).
x || y // Returns true (y is not evaluated).
y || x // Returns true (x and y are evaluated).
y || y // Returns false (y and y are evaluated).

Example usage

if(object != null && object.Property)
// object.Property is never accessed if object is null, because of the short circuit.
    Action1();
else
    Action2();

Stats

Contributors: 4
2016-07-24
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook