The order of the statements in the IF expression

I often do this when necessary to throw a null pointer exception:

// Example #1
if (cats != null && cats.Count > 0)
{
  // Do something
}

In # 1, I always assumed that I cats != nullshould be the first, because the order of operations is evaluated from left to right.

However, unlike example # 1, now I want to do something if the object nullor if it Countis equal to zero, so I use logical OR instead of AND:

// Example #2
if (table == null || table.Rows == null || table.Rows.Count <= 0)
{
  // Do something
}

Does the order of logical comparisons mean? Or can I also change the order and get the same results as in example # 3?

// Example #3
if (table.Rows.Count <= 0 || table.Rows == null || table == null)
{
  // Do something
}

(By the way, I understand that I can rewrite # 2 as shown below, but I think this is messy and I'm still curious about OR statements)

// Example #4
if (!(table != null && table.Rows != null && table.Rows.Count > 0))
{
  // Do something
}
+3
6

, , , && , LHS ( ), || , LHS ( ).

, , .Rows .

+2

:

if (table == null || table.Rows == null || table.Rows.Count <= 0)
{
  // Do something
}

... table.Rows, table.Rows.Count , tables null.

, #, . # - , , , .

:

bool A()
{
    return false;
}

bool B()
{
    return true;
}

//...

if (A() && B())
{
    // do something
}

AND , . , A() false, (, , , , ...) B().

OR (||). - , , .

+11

, # ( ).

- (& &), . AND (&) , - .

OR Conditional-OR.

:

// , , .

if (cats!= null cats.Count > 0) {}

// . - .

if (cats!= null && cats.Count > 0) {}

+2

. . ands , , , ORs , .

evaulation, .

, .

if (null== null || null.Rows == null || null.null.Count <= 0)
{
  // Do something
}

if( true || null.Rows == null || null.null.Count <=0)

true, stop. "null". .

if (null.null.Count <= 0 || null.Rows == null || null== null)
{
  // CRASH... Do something
}
0

, . - , , null Count . DO, , ... , , :

 if (table == null || table.Rows == null || table.Rows.Count <= 0 || ) 
 {}
 else
 { 
  // Do something 
 } 

, , , , , . Rows.

0

.

:

, IF, , IF ... , , .

, , , , , AFAIK.

Edit @JonHanna

I suppose I looked at this from the point of view that the OP stated that it checks the NPE earlier, when necessary (see the first line of his post). Therefore, if its code does not create runtime errors, then order does not mean anything. I can’t imagine why someone would code an IF statement with the thought process "if this IF statement calls NPE" then it will not be evaluated ...

-1
source

Source: https://habr.com/ru/post/1768341/


All Articles