In C#, there is not "or" and "and". The operators '||' and '&&' are 1) optimized variants of '|' and '&', 2) '||' and '&&' are only Boolean operators, but '|' and '&' are also bitwise ones.
Why use Boolean '|' and '&' then? They are really best avoided, but, for completeness of the Boolean arithmetic, they are needed. You will see the difference if you use a Boolean function with a
side effect. Using such functions in a Boolean expression is
highly discouraged, but what happens if you do it? Let's see:
bool result = Left() || Right();
As the operator '||' is optimized, it won't evaluate the redundant operand. If
Left()
returns true, the whole expression will always be true, so the expression evaluation won't call
Right()
. If
Right()
has some side effect, it would be lost (never happen).
Likewise in
bool result = Left() && Right();
if
Left()
returns false, the whole expression is always false, so the expression evaluation won't call
Right()
. If
Right()
has some side effect, it would be lost.
Expressions with '|' or '&' will always evaluate all the operands; this way, both functions will always be called. Same thing goes about properties with the
getters which cause any side effect.
I hope everything is clear now.
—SA[EDIT]Fixed apparent copy-paste errors - Matt Heffron[/EDIT]