What is the difference between the | and || or operators?
Solution 1:
Just like the &
and &&
operator, the double Operator is a "short-circuit" operator.
For example:
if(condition1 || condition2 || condition3)
If condition1 is true, condition 2 and 3 will NOT be checked.
if(condition1 | condition2 | condition3)
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.
No one ever uses the single &
or |
operators though, unless you have a design where each condition is a function that HAS to be executed. Sounds like a design smell, but sometimes (rarely) it's a clean way to do stuff. The &
operator does "run these 3 functions, and if one of them returns false, execute the else block", while the |
does "only run the else block if none return false" - can be useful, but as said, often it's a design smell.
There is a Second use of the |
and &
operator though: Bitwise Operations.
Solution 2:
|| is the logical OR operator. It sounds like you basically know what that is. It's used in conditional statements such as if, while, etc.
condition1 || condition2
Evaluates to true if either condition1 OR condition2 is true.
| is the bitwise OR operator. It's 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 = 00000001
B = 00010000
A | B = 00010001
A = 10001011
B = 00101100
A | B = 10101111
Hopefully that makes sense.
So to answer the last two questions, I wouldn't say there are any caveats besides "know the difference between the two operators." They're not interchangeable because they do two completely different things.