In this case, what is the difference of using | or use double || ?
if (char.IsNumber(e.KeyChar) | e.KeyChar == (char)8 | e.KeyChar == (char)Keys.Escape)
{
e.Handled = false;
return;
}
else
{
e.Handled = true;
return;
}
When using double operators in the case of the OR, what happens is that it stops checking the rest of the conditions if it finds a true one.
In the case of & the same thing happens if it finds a false condition
In your example:
Here it verifies that the three conditions
but:
If the first condition is not met, but the second is, the third condition is not evaluated and the "if" is entered.
According to microsoft:
When using
|
all expressions both left and right. Whereas when using ||, it is only evaluated from left to right.@Sr1871 referenced an answer from SO/English and there is an answer that has an expression that might help:
As already explained in the accepted answer, with the binary operator
|
, all Boolean expressions are evaluated.In contrast, with the conditional operator
||
, what is known as a "short-circuit" evaluation is performed . That is, the evaluation of Boolean expressions stops when the final result of the evaluation can no longer change even if the other expressions were still evaluated.In the example you propose, the difference is practically nil. But the difference is noticeable with this very common example:
In this case, the use of the operator
||
allows to avoid aNullReferenceException
whenobj == null
, because the second expression is not evaluated in that case.In contrast, if the binary operator were used
|
:...then yes
obj == null
, you will receive aNullReferenceException
.Because of this, it is very rare to use the binary operator
|
with Boolean expressions. Most commonly, this operator is used with integer values to perform aOR
bitwise.