Xceedas

Xceedas
xceedas

Tuesday, 9 September 2014

Difference between & and && in C#

I am going to explain a very basic concept of C# in this blog. & and && both are “AND” operators in C# which means that if both conditions are true only then result is true. Normally we use this operator in if statement and check the condition and perform some action. Since I explain that both operators do the same work then what is the difference between them? There is big difference between the executions of these operators. 

Both operators are used like:
  • Condition1 && Condition2
  • Condition1 & Condition2
When && is used, then first condition is evaluated and if it comes out to be false then the second condition is not checked because according to the definition of && operator (AND) if both conditions are true only then && returns true else false. So if condition1 evaluates to false then there is no need for checking the condition2 as it always going to return false. It improves the performance of the application as it skips condition2 when condition1 is false else both conditions will be evaluated.

When & is used then both conditions are checked in every case. It first evaluates condition1, irrespective of its result it will always checks the condition2. Then it compares both outputs and if both are true only then it returns true.

I have created a sample code for verifying this concept. For that I have created two methods one returning True and other returning false.
  1. public static bool ReturnsTrue()  
  2.    {  
  3.        return true;  
  4.    }  
  5. public static bool ReturnsFalse()  
  6.    {  
  7.        return false;  
  8.    }  
  9. if (ReturnsFalse() && ReturnsTrue())  
  10.    {  
  11.        Console.WriteLine("Hit");  
  12.    }  
I have called these methods in if statement and since first condition returns False so ReturnsTrue method will never called (check this by putting debugger on both ReturnsTrue and ReturnsFalse method) and if you call ReturnsTrue method first then second method will always be called.

Now check the if condition with & operator
  1. if (ReturnsFalse() & ReturnsTrue())  
  2.    {  
  3.         Console.WriteLine("Hit");              
  4.    }  
It will always check both conditions and both methods will be called. (Check by applying debugger).

So we should always prefer && operator as it improves performance. & operator should only be used when there is a requirement for checking both conditions.

No comments :