Possible Duplicate:
C# okay with comparing value types to null
I came a cross something I find strange in the C# (4.0) compiler just now.
int x = 0;
if (x == null) // Only gives a warning - 'expression is always false'
x = 1;
int y = (int)null; // Compile error
int z = (int)(int?)null; // Compiles, but runtime error 'Nullable object must have a value.'
If you cannot assign null
to an int
, why does the compiler allow you to compare them (It gives a warning only)?
Interestingly, the compiler does not allow the following:
struct myStruct
{
};
myStruct s = new myStruct();
if (s == null) // does NOT compile
;
Why does the struct
example not compile, but the int
example does?
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.
compareTo(null) should throw a NullPointerException even though e. equals(null) returns false. It is strongly recommended (though not required) that natural orderings be consistent with equals.
Say you have a table with a NULLable column type, and you want to find rows with a NULL value in that column. Since you can't use a equality operator in the WHERE clause (remember, NULL values can't be equated or compared), the right way to compare NULL values is to use the IS and IS NOT operators.
The value NULL does not equal zero (0), nor does it equal a space (' '). Because the NULL value cannot be equal or unequal to any value, you cannot perform any comparison on this value by using operators such as '=' or '<>'.
When the comparison is made, the compiler tries to make it so both operands of the comparison have compatible types if possible.
It had an int
value and a constant null
value (with no particular type). The only compatible type between the two values is int?
so they are coerced to int?
and compared as int? == int?
. 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.
actually compilation allow comparing 'int?' to 'int' not 'int' to null which make sense
e.g.
int? nullableData = 5;
int data = 10;
data = (int)nullableData;// this make sense
nullableData = data;// this make sense
// you can assign null to int
nullableData = null;
// same as above statment.
nullableData = (int?)null;
data = (int)(int?)null;
// actually you are converting from 'int?' to 'int'
// which can be detected only at runtime if allowed or not
and that's what you are trying to do in int z = (int)(int?)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