Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable Types and Operators

Tags:

c#

c#-2.0

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?

like image 935
Gaurav Ahuja Avatar asked Dec 07 '25 00:12

Gaurav Ahuja


1 Answers

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 . . .

like image 160
Sam I am says Reinstate Monica Avatar answered Dec 08 '25 15:12

Sam I am says Reinstate Monica