.Net 2+: why if (1 == null) no longer throws a compiler exception?

I use intas an example, but this applies to any type of value in .Net

In .Net 1, the following would eliminate the compiler exception:

int i = SomeFunctionThatReturnsInt();

if( i == null ) //compiler exception here

Now (in .Net 2 or 3.5) this exception has passed.

I know why this is:

int? j = null; //nullable int

if( i == j )   //this shouldn't throw an exception

The problem is that since int?it is NULL, it intnow has an implicit cast to int?. The syntax above is the compiler magic. In fact, we do:

Nullable<int> j = null; //nullable int

//compiler is smart enough to do this
if( (Nullable<int>) i == j)   

//and not this
if( i == (int) j)

So, when we do i == null, we get:

if( (Nullable<int>) i == null )

Given that C # does the compiler logic to calculate this anyway, why can't it be smart enough not to do this when dealing with absolute values ​​like null?

+5
6

, ; , ; , false. ;

bool oneIsNull = 1 == null;

, : The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type '<null>'.

, , " " , .

+3

... VS2008, .NET 3.5:

    static int F()
    {
        return 42;
    }

    static void Main(string[] args)
    {
        int i = F();

        if (i == null)
        {
        }
    }

warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?'

IL... JIT

L_0001: call int32 ConsoleApplication1.Program::F()
    L_0006: stloc.0 
    L_0007: ldc.i4.0 
    L_0008: ldc.i4.0 
    L_0009: ceq 
    L_000b: stloc.1 
    L_000c: br.s L_000e

?

+3

, , . , , ( .net 3.5).

+1

2.0 . , "1" , (int) Nullable int. , , int , . 2.0:

1 "false", "int" "null" "int?"

+1

(3.5, ) - , 1 == 2, , , .

I suspect that with a full optimization of 3.5, the entire operator will simply be deprived, as it is pretty smart, never true.

Although I may need 1==2to compile (to disable the function block while I'm testing something else, for example), I don't want 1==nullto.

0
source

This should be a compile-time error, because the types are incompatible (value types can never be empty). It is rather sad that it is not.

0
source

All Articles