You are likely using the || and && operator everyday without thinking about what the | and & operators do. This is rightly so, as there are very few cases where you would use | and &.
The double variants (&& and ||) are short-circuits. When using || and the first parameter is true in an if statement, the second condition is not evaluated. Same as if you use the && operator and the first condition is false, the second will not be evaluated. This is an optimisation, but also the way most would expect the code to execute. You can see the examples of this below:
When using the ||
operator the second condition is not evaluated if the first condition is true, as seen below where no exception is thrown:
if (true || MethodThatThrowsAnException()) //MethodThatThrowsAnException is not called
When using the &&
operator the second condition is not evaluated if the first condition is false, as seen below where no exception is thrown:
if (false && MethodThatThrowsAnException()) //MethodThatThrowsAnException is not called
When using a single |
the second condition is evaluated even if the first condition is true, as seen below where an exception will be thrown:
if (true | MethodThatThrowsAnException()) //MethodThatThrowsAnException is called
When using a single &
the second condition is evaluated even if the first condition is false, as seen below where an exception will be thrown:
if (false & MethodThatThrowsAnException()) //MethodThatThrowsAnException is called
So when would you use the & and | operators? Well most situations would seem like a hack where you wish to evaluate a condition even if it does not change the outcome. Using & and | will most likely make your code harder to reason with and could be seen as a misuse, a way to execute code no matter the outcome of the if statement. They can however be used for bitwise operations.
Note: the | and & operator can also be used for bitwise operations, however I do not believe this is what most are looking for when looking for the differences between || and | (or && and &).
I hope you enjoyed this post on the operators: || VS | and && VS &. If you did or have something to add, please let me know in the comments down below! :)
More on operators from my blog: