Asked • 03/18/19

Why doesn't the C# compiler throw for logical comparisons of null?

I was eating lunch with a friend yesterday and they were complaining about `null` in C#. He stated that `null` was illogical. I decided to test his claims, so I tested some simple logical propositions: Console.WriteLine(null == null); //True //Console.WriteLine(null == !!null); //BOOM Console.WriteLine(10 >= null); //False Console.WriteLine(10 <= null); //False Console.WriteLine(!(10 >= null)); //True Console.WriteLine(!(10 <= null)); //True Checking equality seems straightforward and this is what I would expect. The greater/less than statements however are logical contradictions which I find really confusing! Shouldn't these throw? The negation operation throws as you would expect. If I try to run comparisons (aside from equality) using `null` in Ruby or Python I get a type error along the lines of "cannot compare a number to nil". Why doesn't C# do this?

1 Expert Answer

By:

Alexander R. answered • 02/27/22

Tutor
New to Wyzant

Software Engineer by trade looking to share my knowledge

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.