There are two if statements below that have multiple conditions using logical operators. Logically both are same but the order of check differs. The first one works and the second one fails.
I referred MSDN for checking whether the order of execution of the conditions defined; but I could not find.
Consider a multiple check condition that has &&
as the logical operator. Is it guaranteed that it will always check the first condition and if that is not satisfied the second condition will not be checked?
I used to use approach 1 and it works well. Looking for an MSDN reference substantiaing the use.
UPDATE
Refer "short-circuit" evaluation
CODE
List<string> employees = null; if (employees != null && employees.Count > 0) { string theEmployee = employees[0]; } if (employees.Count > 0 && employees != null) { string theEmployee = employees[0]; }
The syntax of a conditional expression consists of a conditional statement in parentheses. This can be just like the conditionals used in an if-else statement. This is followed by a question mark, a value to be set if the condition is true, a colon, and finally a value to be set if the condition is false.
The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int. 4 Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; there is a sequence point after the evaluation of the first operand.
C has the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.
nested-if in C/C++ Nested if statements mean an if statement inside another if statement. Yes, both C and C++ allow us to nested if statements within if statements, i.e, we can place an if statement inside another 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
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