I’m reading an source code, I found a statement like this:
if (Char.IsWhiteSpace(text[i]) | GetSpecialChars.Contains(text[i]))
Initially,I thought it was typo,instead || (or) operator. But for my surprise, it was compiled. how to it’s possible? is | equivalent to || with boolean types?
Thanks in advance.
I’d suggest that it probably is a typo, though it will still work.
The reason boolean
|is so rarely seen is that:||is the only one that is correct. If the expression on the right hand side would throw if the expression on the left-hand was true such as inx == null || x.Length == 0which would successfully return true for a null or zero-length string or array whilex == null | x.Length == 0which would throw an exception for a null string or array as theLengthproperty would still be examined.||will be faster. It might be nothing but a couple of clock cycles faster (though it could also be more if the expression on the rhs is expensive), but it hardly counts as a premature optimisation that we’re all in the habit of using that form. (Just how much effort you put into deciding which goes on the left and which on the right may be another matter).The example in the question falls under point two. The only effect of
|rather than||here in practice is a few nanoseconds of waste. Not that it matters, but it does lead to||being the habit to fall into.(If on the other hand a property called
GetSpecialCharsor a method calledContainshas a side-effect that means it has to be called, that property really needs to be renamed to make it clearer!).About the only time it’s useful is either because we really need some side-effect of the right-hand expression to take place, or in the assignment form based on it,
|=.In the former case, it’s always worth considering an alternative of evaluating both expressions in separate statements and then ORing the result afterwards, to make it clearer that you care about the side-effect as well as the result.
In the latter case, it can make for more readable code, or at least to code that’s more readable to some people! But many find it obscures things.