Short-Circuit Evaluation In C#

Introduction

Hi everyone , in this article we’ll discuss C# short-circuit logical operators && and || in depth. Most of us must have used these operators before, but most people don’t know why we use && instead of &. The use of these operators(&& and ||) is one of the best practices over non short-circuit operators & and |. So we should know how it works, where to use them and how they increase speed of execution. Let’s get started.

What is Short-Circuit in C#?

Short-circuit is a tricky method for evaluating logical operators AND and OR. In this method, the whole expression can be evaluated to true or false without evaluating all sub expressions.

Consider the following c# code snippet using & and |

  1. bool Condition1() { return false; }   
  2. bool Condition2() { return true; }     
  3. public A() {       
  4.    if (Condition1() & Condition2())       
  5.    {           
  6.     //inside code will not execute     
  7.    }      
  8.    if (Condition2() | Condition1())    
  9.    {           
  10.    //inside code will execute      
  11.    }   
  12. }   

While debugging it looks like below,


In the above program both operands Condition1() and Condition2() are evaluated.

For AND operations if any of the operand evaluated to false then total expression evaluated to false then there is no need to evaluate remaining expressions, And in case of OR operation if any of the operand evaluated to true then remaining evaluations can be skipped.

This type of skipping is done through short-circuited evaluation. For that, in the above program, & is replaced with && and | is replaced with ||, then debugging will be like this,


You can see the skipping of evaluations due to short-circuit evaluation. Consider the following example

  1. if (false && Condition1())   
  2. {       
  3. //inside code won't work in any case   
  4. }  

in the above if clause, Condition1() will not be evaluated because whatever the value of Condition1() the whole expression will be false.If we use & instead of &&, it will execute Condition1() also. So always try to stick with short-circuited version. There is one little point you should be aware of, that is Side effect.I will tell you what it means in later parts of this article.

&& Vs & or || Vs |

First difference between them is short-circuit evaluation. Before getting into the remaining differences let’s grab some basics that might be helpful to understand the rest.

AND, OR operators can be found in the following ways,

  • & ( single ampersand ) – Logical AND operator
  • | ( single pipeline) – Logical OR operator

    Both of these operators are non short-circuit in nature.

  • && ( double ampersand ) – Conditional AND operator
  • || ( double pipeline) – Conditional OR operator

    Both of these are short-circuited operators and collectively knows as Conditional Logical Operators.

Order of Evaluation

Order of execution of any of these operators are from left to right. In the following lines of code,

  1. if(Expression1() && Expression2() && ....)   
  2. { }  

Expression1 will be evaluated first then Expression2 and so on.

Remaining Differences

& and | can be used as both Boolean operand as well as Numeric operands like Bit-wise operation. But && and || operands can only be applied to Boolean operands.

  • & operator can be used as either unary or binary operator. that is, unary & can be used to get address of it’s operand in unsafe context.

Examples

as Binary Operator

Bit wise Operation
  1. int a = 60;            /* 60 = 0011 1100 */    
  2. int b = 13;            /* 13 = 0000 1101 */   
  3. int c = a & b;             /* 12 = 0000 1100 */  

Logical Operation

  1. if(true & false)   
  2. //do something }  

as Unary Operator

& can be used as addressof-expression in unsafe mode. For more details follow this link from msdn.

  1. int i;   
  2. unsafe 
  3. {     
  4.  int* p = &i;   
  5.    *p = 123;   
  6. }  

How to Use && in C#

In this section I will tell you how to use && with the help of some practical examples. In the same way you can understand how you can make use of || operator.

Prevent Exceptions

If you are asked to write a c# program for checking whether the 5th element in a given array is odd or not, it is better to implement the following if clause.

  1. if (array.Count() >= 5 && array[4] % 2 == 1)    
  2.  {      
  3.  //print message here   
  4. }     

If the && were replaced with &.it will cause Index was outside the bounds of the array exception when array does not contains 5 elements.

Ordering Expressions to Reduce Performance Impact

Like we said, order of evaluation is from left to right.So if you have a series of operands for && operator as below and each of them are independent on other expressions:

  1. if (Validations() && CheckUserExistance() && ..... && IsAuthorised())   
  2. {       
  3. //Some Operations   
  4. }  

It is better to arrange them in the order of their complexity. For example, if you are dealing with a project including lots of DataBase interactions, move all those DB methods to right side of clause, so that in many of the cases these methods won’t be executed if preceding operands were false.

Side Effect

Consider the following example

  1. int i = 0;  
  2.  if (true && (++i < 50)) {     
  3.   //code goes here   
  4. }  
  5.  //value of i is 1  
  6. if (false && (++i < 50)) {   
  7.     //inside code will not execute   
  8. }   
  9. // value of i remains as 1  

As a result of short circuiting the second operand in the second if clause will not execute, so value of i remains same as before. This effect is called Side effect, I would say it is a Right Side effect right?:)

So when you use them, you should be aware of this effect and these effects are seen in rare situations.

Conclusion

Short circuited logical operators in C# are && and ||, They are efficient and fast versions of logical operators in C#. So it is a good practice to use them and there is no reason nto to use them.

Original article link - short-circuit-evaluation-csharp by DotnetMob

NOTE : all of the code snippets given in this are well tested.