Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does comparison operator works with null int?

Tags:

c#

nullable

I am starting to learn nullable types and ran into following behavior.

While trying nullable int, i see comparison operator gives me unexpected result. For example, In my code below, The output i get is "both and 1 are equal". Note, it does not print "null" as well.

int? a = null; int? b = 1;  if (a < b)     Console.WriteLine("{0} is bigger than {1}", b, a); else if (a > b)     Console.WriteLine("{0} is bigger than {1}", a, b); else     Console.WriteLine("both {0} and {1} are equal", a, b); 

I was hoping any non-negative integer would be greater than null, Am i missing something here?

like image 527
Ron5504 Avatar asked Apr 03 '13 02:04

Ron5504


People also ask

Can I compare int with null?

Some int value as an int? is definitely non-null and null is definitely null. The compiler realizes that and since a non-null value is not equal to a definite null value, the warning is given. The compiler also optimizes this away because it is always false. It won't even load the x variable at all.

How are NULLs treated in comparison operators?

For comparison operators in SQL, NULL can be compared usingIS or IS NOT operator. SQL treats each NULL as a distinct value, so =,<,> can not beused for comparison.In general, NULL values are discarded when aggregate functions are applied to aparticular column.

Can I compare with Null?

You can't compare with NULL. You need is. null to test if something is a reference to the NULL object.

Which operator is used to compare a value with a null value?

ISNULL() can be used instead of = to test whether a value is NULL . (Comparing a value to NULL using = always yields NULL .) The ISNULL() function shares some special behaviors with the IS NULL comparison operator.


1 Answers

According to MSDN - it's down the page in the "Operators" section:

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 !=

So both a > b and a < b evaluate to false since a is null...

like image 105
nkvu Avatar answered Oct 05 '22 07:10

nkvu