I'm using int
as an example, but this applies to any value type in .Net
In .Net 1 the following would throw a compiler exception:
int i = SomeFunctionThatReturnsInt();
if( i == null ) //compiler exception here
Now (in .Net 2 or 3.5) that exception has gone.
I know why this is:
int? j = null; //nullable int
if( i == j ) //this shouldn't throw an exception
The problem is that because int?
is nullable and int
now has a implicit cast to int?
. The syntax above is compiler magic. Really we're doing:
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 now, when we do i == null
we get:
if( (Nullable<int>) i == null )
Given that C# is doing compiler logic to calculate this anyway why can't it be smart enough to not do it when dealing with absolute values like null
?