Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does >= return false when == returns true for null values?

I have two variables of type int? (or Nullable<int> if you will). I wanted to do a greater-than-or-equal (>=) comparison on the two variables but as it turns out, this returns false if both variables are null, while obviously the == operator returns true.

Can someone explain to me why that is logical because the semantical definition of the >= operator contains the word "or"?

like image 259
Koen Avatar asked Dec 09 '10 15:12

Koen


People also ask

Why is null == false false?

null is one of JavaScript's primitive values. It is neither equal to boolean true nor equal to boolean false because it's value is undefined.

Why null === null is true?

2. How to check for null. missingObject === null evaluates to true because missingObject variable contains a null value. If the variable contains a non-null value, like an object, the expression existingObject === null evaluates to false .

IS null value true or false?

The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations.

IS null == false C#?

The way you typically represent a “missing” or “invalid” value in C# is to use the “null” value of the type. Every reference type has a “null” value; that is, the reference that does not actually refer to anything.


1 Answers

There was a huge debate about this oddity when the feature was originally designed back in C# 2.0. The problem is that C# users are completely used to this being meaningful:

if(someReference == null) 

When extending equality to nullable value types, you have the following choices.

  1. Nullable equality is truly lifted. If one or both of the operands is null then the result is neither true, nor false, but null. In this case you can either:

    • a) Make it illegal to have a nullable value type equality in an if statement, because the if statement needs a bool, not a nullable bool. Instead, require everyone to use HasValue if they want to compare to null. This is verbose and irritating.

    • b) Automatically convert null to false. The downside of this is that x==null returns false if x is null, which is confusing and works against people's understanding of null comparisons with reference types.

  2. Nullable equality is not lifted. Nullable equality is either true or false, and comparison to null is a null check. This makes nullable equality inconsistent with nullable inequality.

None of these choices is obviously correct; they all have pros and cons. VBScript chooses 1b, for example. After much debate the C# design team chose #2.

like image 183
Eric Lippert Avatar answered Oct 13 '22 06:10

Eric Lippert