Question

I was reading about Nullable Types and Operators from Wrox and came across the following statement:

When comparing nullable types, if only one of the operands is null, the comparison will always equate to false. This means that you cannot assume a condition is true just because its opposite is false.

Now, I get what the first statement means but didn't get the second statement. Could you please elaborate?

Was it helpful?

Solution

It appears like the quote is saying that any comparison at all with a null type will return null, regardless of the operand.

So something like (null != 5) Would return false, where (null == 5) would also return false.


Now, the funny thing is, that when I ran a program, null != 5 returned true, so while I can't verify that statement for c# 2.0, it's definitely not true anymore in c# 4.0 +

This is the sample code I've used:

int? a = null;

int? b = 5;

if (a != b)
{
    Console.WriteLine("A != B");
}
if (a == b)
{
    Console.WriteLine("A == B");
}

This is the output

A != B
Press any key to continue . . .

OTHER TIPS

That quote is wrong, MSDN is the official source: http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx

When you perform comparisons with nullable types, if the value of one of the nullable types is null and the other is not, all comparisons evaluate to false except for != (not equal).

The second statement simply means that a comparison and its opposite may be both false, eg a>=b and a<b are both false.

Here's the logic. Null kind of means an unknown value. Now try to calculate 5<null, 5<=null, 5==null, 5>=null, 5>null. You can't exactly calculate any of these, they are not true or false either, they are unknown, but false makes a bit more sense than true. The exception is 5!=null. An exact number is not unknown, so it makes a bit more sense that it's true than false. So == and != are the opposite of each other, it's the easy case, but you can't say that for greater-less comparisons. It was a design choice when they made C#/.NET.

SQL on the other hand got it quite right I think with 3-valued-logic, see here: http://en.wikipedia.org/wiki/Null_%28SQL%29#Comparisons_with_NULL_and_the_three-valued_logic_.283VL.29

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top