Why is &&
preferable to &
and ||
preferable to |
?
I asked someone who\'s been programming for years a
If you are an old-timer C programmer, be careful. C# has really surprised me.
MSDN says for the |
operator:
Binary | operators are predefined for the integral types and bool. For integral types, | computes the bitwise OR of its operands. For bool operands, | computes the logical OR of its operands; that is, the result is false if and only if both its operands are false.
(Emphasis is mine.) Boolean types are handled specially, and in this context the question only starts to make sense, and the difference is, as other already expained in their answers:
&&
and||
are short-circuiting.&
and|
evaluate both operands.
and what's preferable depends on many things like side-effects, performance and code readability, but generally the short-circuiting operators are preferable also because they are better understood by people with a similar background like me.
The reason is: I would argument like this: Since there is no real boolean type in C, you could use the bitwise operator |
and have its result evaluated as truthy or falsy in an if condition. But this is the wrong attitude for C#, because there is already a special case for boolean types.