If you have an if-statement in C# that checks multiple conditions:
if (a == 5 && b == 9) { ... }
Does b == 9 still get checked if a == 5 condition is false, or does it automatically exit since there's no way this could pass anymore?
Similarly, for an OR if-statement:
if (a == 5 || b == 9) { ... }
Will b == 9 still get checked if a == 5 is true?
Using the AND operator, according to the boolean logic, all the conditions must be evaluated to TRUE. If only one of them isn't satisfied, the result of the conditions will be FALSE.
It does automatically exit, because the first condition is false and the result is already known.
For the OR operator, you need that, at least, one of the conditions is TRUE and your logic will be executed. If the first one is not satisfied, the application will check the other conditions.
No, it won't be checked, because the first condition is TRUE and then it's not necessary to check another condition.
For :
if (a == 5 && b == 9) { ... }
If
a == 5
isfalse
no any other control will be executed on that line.For:
if (a == 5 || b == 9) { ... }
Pass inside immediately, as first condition already satisfies requirements.
Conceptually,
&&
and||
short-circuit.But since you don't have any side-effects there, the JIT compiler is free to remove the short-circuiting. I don't know whether it actually does so or not.
in AND check
a==5
if is true then will go tob==9
else will not go tob==9
. in OR: it will checka==5
andb==9
.Both
&&
and||
is "short-circuiting" operators, which means that if the answer is known from the left operand, the right operand is not evaluated.This means that:
b
will not be evaluated ifa
is false, since the final answer is already known.Likewise:
b
will not be evaluated ifa
is true, since the final answer is already known.If you want both operands to be evaluated, use the
&
and|
operators instead.The bonus of this is that you can write expressions that would fail if all operands was evaluated. Here's a typical if-statement:
If a was null, and the expression would go on to evaluate
a.SomeProperty
, it would throw aNullReferenceException
, but since&&
short-circuits, ifa
isnull
, the expression will not evaluate the rest and thus not throw the exception.Obviously, if you replace
&&
with&
, it will throw that exception if eithera
ora.SomeProperty
isnull
.Short-cirtuiting is defined by standard. Otherwise it would be impossible to say what is the outcome of expression such as:
In some C# compilers it would work fine, in some others it would cause an exception. That's why the standard is there to define common behavior.
EDIT: clarified last statement.