-1

For the following code:

bool assertTest(int? n1, int? n2) {
  return (n1 == null) || (n1 != null && n2 != null);
}

there is a warning at n1 != null saying The operand can't be null, so the condition is always true. Why does this warning show up? n1 is obviously nullable.

Naveen
  • 1,363
  • 7
  • 17
  • 28

1 Answers1

1

The boolean operation are lazy, it means that if you evaluate a || b and a is true, then b is not even evaluated.

In your case, if b = (n1 != null && n2 != null) is evaluated, it means a = (n1 == null) = false, which means n1 != null so the check n1 != null will always be true.

Valentin Vignal
  • 6,151
  • 2
  • 33
  • 73
  • Hi! Thank you, it makes sense. I changed the order in which the two expressions are arranged and the warning vanished. – Naveen Mar 20 '21 at 08:32
  • 2
    You should just remove the redundant comparison instead of changing the order: `return n1 == null || n2 != null;`. – jamesdlin Mar 20 '21 at 09:08