1. if statement
2. if else statement
3. Difference between && and &
4. Difference between | | and |
Difference between && and &:
Both operators are used like:
- Condition1 && Condition2
- Condition1 & Condition2
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");
- }
Now check the if condition with & operator
- if (ReturnsFalse() & ReturnsTrue())
- {
- Console.WriteLine("Hit");
- }
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:
Post a Comment