I have always used || (two pipes) in OR expressions, both in C# and PHP. Occasionally I see a single pipe used: |. What is the difference between those two usages? Are there any caveats when using one over the other or are they interchangeable?
I have always used || (two pipes) in OR expressions, both in C# and
Share
Just like the
&and&&operator, the double Operator is a ‘short-circuit’ operator.For example:
If condition1 is true, condition 2 and 3 will NOT be checked.
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 is null, the if-statement will stop after
class != nullis false. If you only use &, it will try to checkclass.someVarand you get a niceNullReferenceException. 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.