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?
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
intvalue and a constantnullvalue (with no particular type). The only compatible type between the two values isint?so they are coerced toint?and compared asint? == int?. Someintvalue as anint?is definitely non-null andnullis definitely null. The compiler realizes that and since a non-null value is not equal to a definitenullvalue, the warning is given.