I was wondering what happens when a program processes an if-structure with multiple conditions. I have an idea, but I'm not sure about it. I'll give an example:
List<string> myTestList = null;
if (myTestList != null && myTestList.Count > 0)
{
//process
}
The list is null. When processing the if statement, will it go from left to right exiting the if as soon as one condition is false?
I've tried it and seems to throw no errors, so I assume the above explains it, but I'm not sure.
It is the &&
that is important. This is short-circuiting, so the Count
is never evaluated; The conditions are evaluated left-to-right.
There is also a non-short-circuiting operator (&
), but it is very rare to see in an if test; it is mainly intended for bitwise operations (on int
etc).
From the spec:
Conditional logical operators
The
&&
and||
operators are called the conditional logical operators. They are also called the “short-circuiting” logical operators....
The
&&
and||
operators are conditional versions of the&
and|
operators:
- The operation
x && y
corresponds to the operationx & y
, except thaty
is evaluated only ifx
is notfalse
.- The operation
x || y
corresponds to the operationx | y
, except thaty
is evaluated only ifx
is nottrue
.
In most (but not all) modern languages, there is a feature called "short circuit boolean evaluation". This means that if the first part of an &&
condition is false, then the second part is not evaluated at all.
A similar feature applies to ||
, where if the first part is true, the second part is not evaluated.
Note that this feature is not limited to if
statements. The following is also valid and won't try to reference Count
if myTestList
is null
:
bool b = myTestList != null && myTestList.Count > 0;
It's short-circuited.
a && b
if a
is false, b
will not be evaluated. We can use this behavior because the expression will always be false.
Similarly,
a || b
if a
is true, b
will not be evaluated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With