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?
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.
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.
You can't compare with NULL. You need is. null to test if something is a reference to the NULL object.
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.
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 tofalse
except for!=
So both a > b
and a < b
evaluate to false
since a
is null...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With