Wednesday, April 8, 2015

&& and || - C# Short Circuited Logical Operators


Please find original post from here

Table of Contents

  • Introduction
  • What is Short Circuiting in C#?
  • && Vs & or || Vs |
  • How to Use && in C#
  • Side Effect
  • Conclusion


Introduction

          Hi everyone, in this article we'll discuss C# short circuited logical operators && and || in depth. Most of us must have used these && and || operators but many of them don't think about why we use && not & instead.Use of these operators is one of the best practice in c# over non short circuited operators & and |. So you should know how it works, where to use them and how they increase speed of execution. let's get started.

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

What is Short Circuiting in C#?

Short circuiting is a tricky method of evaluating logical operators AND and OR. In this method, whole expression can be evaluated to true or false without evaluating the every expressions in some cases.

Consider  following c# code snippet using & and |

bool Condition1() { return false; }
bool Condition2() { return true; }

public A()
{
    if (Condition1() & Condition2())
    {
        //inside code will not execute
    }

    if (Condition2() | Condition1())
    {
        //inside code will execute
    }
}
While debugging it looks like below
Image Showing Debugging Of Non Short Circuited Operators In C#
Debugging Of Non Short Circuited Operators In C#

        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 or operands, And that of OR operation if any of the operand evaluated to true then remaining evaluation 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
Image Showing Debugging Of Short Circuited Operators
Debugging Of  Short Circuited Operators In C#

You can see skipping of evaluations due to short circuiting.Short circuited version of logical operators are efficient and faster.

Consider following example

if (false && Condition1())
{
    //inside code will execute in any case
}
in the above if clause, Condition1() will not be evaluated because whatever be the value of Condition1() whole expression will be false.If we use & instead of && Condition1() get evaluated which can be expensive in some cases.So always try to stick with short circuited version, There is one little point you should aware of, when you use short circuited logical operators that is Side effect.I will tell you what it means in later parts of this article.

&& Vs & or || Vs |

Please find original post from here
We have discussed that short circuiting, count it as the first difference between them. Before getting into 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 circuited in nature.

&& ( double ampersand ) - Conditional AND operator
|| ( double pipeline) - Conditional OR operator
Both of these are short circuited logical 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

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

Expression1 will be evaluated first then Expression2 and so on.

Remaining Differences

  • & and | can have both Boolean operands as well as Numeric operands for Bit-wise operation But && and || operands can only be applied to Boolean operands.
  • & operator can be used as either unary or binary operator. ie, unary & can be used to get address of it's operand in unsafe context.

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.

1.Preventing Exceptions


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


if (array.Count() >= 5 && array[4] % 2 == 1)
{
    //print message here
}
If the && were replaced with &.it will cause Index was outside the bounds of the array exception when array does not contains 5 elements.

2.Ordering Expressions to Reduce Performance Impact


I already mentioned that order of evaluation is from left to right in these operators.So if you have a series of operands for && operator as below and each of them are independent of each other.

if (Validations() && CheckUserExistance() && ..... && IsAuthorised())
{
    //Some Operations
}

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

Side Effect


Consider the following example 

int i = 0;
            if (true && (++i < 50))
            {
                //code goes here
            }
            //value of i is 1
            if (false && (++i < 50))
            {
                //inside code will not execute
            }
            // value of i remains as 1

As a result of short circuiting second operand in 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 aware of this effect and these effects are practically seen in rare situations.


Conclusion

Please find original post from here

Short circuited logical operators in C# are && and ||, They are efficient and fast version of logical operators in C#.So it is a good practice to use them and there is no reason no to use them.side effect is a byproduct of short circuiting but it is rare.

 I have put my valuable time and effort in making the article informative so please leave your comments below 
-- Done.Thanks For Reading --
»Keep Sharing and Learning   «

4 comments: