Possible duplicate:
C # ok with comparing value types with zero
I came up with something that now seems strange to me in the C # compiler (4.0).
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 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)
Why doesn't the struct example compile, but does the int example do?
source share