Problem
I’m learning about nullable types and came into the following behavior.
When I try nullable int, I notice that the comparison operator produces an unexpected result. For example, the output of my code below is “both and 1 are equal.” It’s worth noting that it doesn’t 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);
Am I missing something here? I was hoping that any non-negative integer would be bigger than null.
Asked by Ron5504
Solution #1
It’s down the page in the “Operators” section, according to MSDN:
Because an is null, both a > b and a b evaluate to false…
Answered by nkvu
Solution #2
As MSDN says
int? num1 = 10;
int? num2 = null;
if (num1 >= num2)
{
Console.WriteLine("num1 is greater than or equal to num2");
}
else
{
// This clause is selected, but num1 is not less than num2.
Console.WriteLine("num1 >= num2 returned false (but num1 < num2 also is false)");
}
if (num1 < num2)
{
Console.WriteLine("num1 is less than num2");
}
else
{
// The else clause is selected again, but num1 is not greater than
// or equal to num2.
Console.WriteLine("num1 < num2 returned false (but num1 >= num2 also is false)");
}
if (num1 != num2)
{
// This comparison is true, num1 and num2 are not equal.
Console.WriteLine("Finally, num1 != num2 returns true!");
}
// Change the value of num1, so that both num1 and num2 are null.
num1 = null;
if (num1 == num2)
{
// The equality comparison returns true when both operands are null.
Console.WriteLine("num1 == num2 returns true when the value of each is null");
}
/* Output:
* num1 >= num2 returned false (but num1 < num2 also is false)
* num1 < num2 returned false (but num1 >= num2 also is false)
* Finally, num1 != num2 returns true!
* num1 == num2 returns true when the value of each is null
*/
Answered by Parimal Raj
Solution #3
To summarize, every inequality comparison with null (>=,,=, >), even if both operands are null, returns false. i.e.
null > anyValue //false
null <= null //false
With null (==,!=), any equality or non-equality comparison works ‘as intended.’
null == null //true
null != null //false
null == nonNull //false
null != nonNull //true
Answered by GDS
Solution #4
When comparing C# to SQL, there are a few things to keep in mind.
a=null and b=null in C# = a==b = true
a=null and b=null => a==b => false SQL: a=null and b=null
Answered by Gunnar Siréus
Post is based on https://stackoverflow.com/questions/15777745/how-does-comparison-operator-works-with-null-int