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?