Alex Rivera | Logout

C# Nullable Equality Operations, Why does null <= null resolve as false?

Asked 2011-01-19T00:43:00.367
40

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?

Edit
Report

1 Answer

30

A number of answers appeal to the spec. In what turns out to be an unusual turn of events, the C# 4 spec does not justify the behaviour specifically mentioned of comparison of two null literals. In fact, a strict reading of the spec says that "null == null" should give an ambiguity error! (This is due to an editing error made during the cleanup of the C# 2 specification in preparation for C# 3; it is not the intention of the spec authors to make this illegal.)

Read the spec carefully if you don't believe me. It says that there are equality operators defined on int, uint, long, ulong, bool, decimal, double, float, string, enums, delegates and objects, plus the lifted-to-nullable versions of all the value type operators.

Now, immediately we have a problem; this set is infinitely large. In practice we do not form the infinite set of all operators on all possible delegate and enum types. The spec needs to be fixed up here to note that the only operators on enum and delegate types which are added to the candidate sets are those of enum or delegate types that are the types of either argument.

Let's therefore leave enum and delegate types out of it, since neither argument has a type.

We now have an overload resolution problem; we must first eliminate all the inapplicable operators, and then determine the best of the applicable operators.

Clearly the operators defined on all the non-nullable value types are inapplicable. That leaves the operators on the nullable value types, and string, and object.

We can now eliminate some for reasons of "betterness". The better operator is the one with the more specific types. int? is more specific than any of the other nullable numeric types, so all of those are eliminated. String is more specific than object, so object is eliminated.

That leaves equality operators for string, int? and bool? as the applicable operators. Which one is the best? None of them is be

answered 2011-01-19T02:55:40.037

Your Answer