3

Here is a C# code fragment that compares to nullables that contains the null value.

int? v1 = null;
int? v2 = null;
Console.WriteLine(v1 > v2); /* False (as expected) */
Console.WriteLine(v1 == v2); /* True (as expected) */
Console.WriteLine(v1 > v2 || v1 == v2); /* True (as expected) */
Console.WriteLine(v1 >= v2); /* False Why? */

The question relates to the last row, why is the (>=) operator does not behave like (> || ==) combination.

Ilan
  • 624
  • 6
  • 11
  • 2
    As per the [second answer](https://stackoverflow.com/a/41051545/993547): "To summarise: any inequality comparison with null (>=, <, <=, >) returns false even if both operands are null." – Patrick Hofman Jan 10 '18 at 12:29
  • That answer really seems to just repeat OP's question though. All it says is basically "null >= null will always be false" without explaining *why*, which I think is what OP really wants to understand. Unfortunately, I think "because the spec says so" is going to be the ultimate answer. – Bradley Uffner Jan 10 '18 at 12:32
  • Thanks. Saw this answer but missed the last one. – Ilan Jan 10 '18 at 12:33
  • null values for comparison return false. Null is not a numeric value which >= is operating on. There is a pretty big debate on this subject. – Josh Adams Jan 10 '18 at 12:33
  • 1
    Also read Eric Lipperts blog on this: https://ericlippert.com/2015/08/31/nullable-comparisons-are-weird/ – Patrick Hofman Jan 10 '18 at 12:33
  • And more here: https://stackoverflow.com/q/4730648/993547 – Patrick Hofman Jan 10 '18 at 12:37
  • A little investigation shows that using Nullable.Compare works as expected in all scenarios. Console.WriteLine(Nullable.Compare(v1, v2) == 0); // True as expected Console.WriteLine(Nullable.Compare(v1, 1) < 0); // True as expected Console.WriteLine(Nullable.Compare(1, v2) > 0); // True as expected – Ilan Jan 10 '18 at 12:59

0 Answers0