Comparing "int" with "null" compilation

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) // does NOT compile ; 

Why doesn't the struct example compile, but does the int example do?

+6
source share
2 answers

When the comparison is performed, the compiler tries to make both comparison operands have compatible types, if possible.

It had an int value and a null constant (without a specific type). The only compatible type between these two values ​​is int? , so they are forcibly bound to int? and are compared as int? == int? int? == int? . Some int value like int? definitely not null, and null definitely null. The compiler understands this, and since a nonzero value is not equal to a specific null value, this warning is provided.

+7
source

Actual compilation allows you to compare "int?" to 'int' not 'int' to zero which make sense

eg.

  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 what are you trying to do in int z = (int)(int?)null;

+1
source

All Articles