Author Topic: What is difference between “&& ” , “& ”,"||" and "|" operators in C#?  (Read 10146 times)

Offline admin

  • Administrator
  • Sr. Member
  • *****
  • Posts: 296
    • View Profile
What is difference between “&& ” , “& ”,"||" and "|" operators in C#?
1 - In the conditional statements:

When using the && operator the compilier uses short circuit logic, e.g.
it the first condition is false, the second one is not evaluated.
but when using the & operator the compilier evaluate both conditions even the first condition is false.

just like the & and && operator, the double Operator || is a "short-circuit" operator
For example:

if(condition1 || condition 2 || condition 3)If condition1 is true, condition 2 and 3 will NOT be checked.

if(condition1 | condition 2 | condition 3)This will check conditions 2 and 3, even if 1 is already true. As your conditions can be quite expensive functions, you can get a good performance boost by using them.

There is one big caveat, NullReferences or similar problems. For example:

if(class != null && class.someVar < 20)If class is null, the if-statement will stop after "class != null" is false. If you only use &, it will try to check class.someVar and you get a nice NullReferenceException. With the Or-Operator that may not be that much of a trap as it's unlikely that you trigger something bad, but it's something to keep in mind.

2- There is a Second use of the | and & operator though: Bitwise Operations.

 | is the bitwise OR operator. Its used to operate on two numbers. You look at each bit of each number individually and, if one of the bits is 1 in at least one of the numbers, then the resulting bit will be 1 also. Here are a few examples:

A = 01010101
B = 10101010
A | B = 11111111
A & B = 00000000
A = 00000001
B = 00010000
A | B = 00010001
A & B = 00000000
A = 10001011
B = 00101100
A | B = 10101111
A & B = 00001000

Hopefully that makes sense.

« Last Edit: October 26, 2008, 05:41:25 PM by admin »