Why is it that in .NET
null >= null
resolves as false, but
null == null
resolves as true?
In other words, why isn’t null >= null equivalent to null > null || null == null?
Does anyone have the official answer?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This behaviour is defined in the C# specification (ECMA-334) in section 14.2.7 (I have highlighted the relevant part):
In particular, this means that the usual laws of relations don’t hold;
x >= ydoes not imply!(x < y).Gory details
Some people have asked why the compiler decides that this is a lifted operator for
int?in the first place. Let’s have a look. 🙂We start with 14.2.4, ‘Binary operator overload resolution’. This details the steps to follow.
First, the user-defined operators are examined for suitability. This is done by examining the operators defined by the types on each side of
>=… which raises the question of what the type ofnullis! Thenullliteral actually doesn’t have any type until given one, it’s simply the “null literal”. By following the directions under 14.2.5 we discover there are no operators suitable here, since the null literal doesn’t define any operators.This step instructs us to examine the set of predefined operators for suitability. (Enums are also excluded by this section, since neither side is an enum type.) The relevant predefined operators are listed in sections 14.9.1 to 14.9.3, and they are all operators upon primitive numeric types, along with the lifted versions of these operators (note that
strings operators are not included here).Finally, we must perform overload resolution using these operators and the rules in 14.4.2.
Actually performing this resolution would be extremely tedious, but luckily there is a shortcut. Under 14.2.6 there is an informative example given of the results of overload resolution, which states:
Since both sides are
nullwe can immediately throw out all unlifted operators. This leaves us with the lifted numeric operators on all primitive numeric types.Then, using the previous information, we select the first of the operators for which an implicit conversion exists. Since the null literal is implicitly convertible to a nullable type, and a nullable type exists for
int, we select the first operator from the list, which isint? >= int?.