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.
- public static bool ReturnsTrue()
- {
- return true;
- }
- public static bool ReturnsFalse()
- {
- return false;
- }
- if (ReturnsFalse() && ReturnsTrue())
- {
- Console.WriteLine("Hit");
- }
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
- if (ReturnsFalse() & ReturnsTrue())
- {
- Console.WriteLine("Hit");
- }
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.