Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"If" statement - Order of validation of objects?

Tags:

c#

Simple question about the order of an IF statement in C#.NET

if (Company !=null && Company.ID > 0)
{
}

Does C# work from left to right, and therefore make the check on Company.ID valid?

Thanks.

like image 702
adamwtiko Avatar asked Aug 24 '10 12:08

adamwtiko


3 Answers

Essentially, yes.

The if statement expects a boolean operator within the parentheses to determine evaluation of the next statement.

Using the && operator, if the first boolean check Company !=null is false, it will statement returning false, and not execute the other (Company.ID > 0).

Also (for reference), using the || operator will return true after the first statement if it is true and not evaluate the second.

like image 93
cjk Avatar answered Oct 24 '22 04:10

cjk


MSDN:

The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary.

like image 6
Paul Rubel Avatar answered Oct 24 '22 03:10

Paul Rubel


The && operator is a so-called short-circuit operator. It tests the statements from left to right and stops testing once one of the tests fails. If you want every test to be run, use the & operator.

More info can be found here

like image 3
rickythefox Avatar answered Oct 24 '22 03:10

rickythefox