Short-circuiting in C#

Jun 13, 2014

There will be lot of situations when you have introduced boolean expressions in your code and in good times you might have also combined more than one boolean expressions to control your program flow.

Boolean Expression

Any expression that can produce a boolean result can be considered as boolean expression. The end result will be boolean, i.e true or false.

For example:

	x == y

You can use Greater than >, Smaller than <, Greater than or equal to >=, Smaller than or equal to <=, equal to ==, Not equal to != equality operators to create a boolean expression.

Combining Boolean Expression

You can combine more than one boolean expressions using OR - ||, AND - && and EXCLUSIVE OR - ^ boolean operators.

Short-circuiting - OR (||) boolean operator

The OR - || boolean operator when applied returns true when any one of the two operand (or boolean expression) or both operand evaluates to true.

If both operand evaluates to false, it will return false.

Example:

  bool leftOperand = true;
  bool rightOperand = false;
  
  bool result = leftOperand || rightOperand;

In above code the result will contain value true. If the left operand (or boolean expression) is true, runtime will not evaluate right operand.

This is called SHORT-CIRCUITING when using OR (||) boolean operator

Short-circuiting - AND (&&) boolean operator

The AND - && boolean operator when applied returns true only when both operand (or boolean expression) evaluates to true.

If any one of the operand evaluates to false, it will return false.

Example:

  bool leftOperand = false;
  bool rightOperand = true;
  
  bool result = leftOperand || rightOperand;

In above code the result will contain value false. If the left operand (or boolean expression) is false, runtime will not evaluate right operand.

This is called SHORT-CIRCUITING when using AND (&&) boolean operator

Short-circuiting - EXCLUSIVE OR (^) boolean operator

The EXCLUSIVE OR - ^ boolean operator when applied returns true only when only one (excatly one, any one) operand (or boolean expression) evaluates to true.

If both the operand evaluates to true or false, it will return false.

Example:

  bool leftOperand = false;
  bool rightOperand = true;
  
  bool result = leftOperand || rightOperand;

In above code the result will contain value true. Due to this nature of XOR boolean operation, runtime will not perform short-circuiting here.

Happy coding !!