Execution order of conditions in C# If statement
The && and || operators short-circuit. That is:
1) If && evaluates its first operand as false, it does not evaluate its second operand.
2) If || evaluates its first operand as true, it does not evaluate its second operand.
This lets you do null check && do something with object, as if it is not null the second operand is not evaluated.
You should use:
if (employees != null && employees.Count > 0)
{
string theEmployee = employees[0];
}
&&
will shortcircuit and employees.Count
will not be execucted if employees
is null
.
In your second example, the application will throw an exception if employees
is null
when you attempt to Count
the elements in the collection.
http://msdn.microsoft.com/en-us/library/2a723cdk(v=vs.71).aspx
The conditions are checked left to right. The &&
operator will only evaluate the right condition if the left condition is true.
Section 5.3.3.24 of the C# Language Specification states:
5.3.3.24 && expressions
For an expression expr of the form
expr-first && expr-second
:· The definite assignment state of v before
expr-first
is the same as the definite assignment state of v before expr.· The definite assignment state of v before
expr-second
is definitely assigned if the state of v afterexpr-first
is either definitely assigned or “definitely assigned after true expression”. Otherwise, it is not definitely assigned.· The definite assignment state of v after expr is determined by:
o If the state of v after
expr-first
is definitely assigned, then the state of v after expr is definitely assigned.o Otherwise, if the state of v after
expr-second
is definitely assigned, and the state of v afterexpr-first
is “definitely assigned after false expression”, then the state of v after expr is definitely assigned.o Otherwise, if the state of v after
expr-second
is definitely assigned or “definitely assigned after true expression”, then the state of v after expr is “definitely assigned after true expression”.o Otherwise, if the state of v after
expr-first
is “definitely assigned after false expression”, and the state of v afterexpr-second
is “definitely assigned after false expression”, then the state of v after expr is “definitely assigned after false expression”.o Otherwise, the state of v after expr is not definitely assigned.
So this makes it clear that expr-first is always evaluated and if true then, and only then, expr-second is also evaluated.