I ran into this today and have no idea why the C# compiler isn't throwing an error.
Int32 x = 1;
if (x == null)
{
Console.WriteLine("What the?");
}
I'm confused as to how x could ever possibly be null. Especially since this assignment definitely throws a compiler error:
Int32 x = null;
Is it possible that x could become null, did Microsoft just decide to not put this check into the compiler, or was it missed completely?
Update: After messing with the code to write this article, suddenly the compiler came up with a warning that the expression would never be true. Now I'm really lost. I put the object into a class and now the warning has gone away but left with the question, can a value type end up being null.
public class Test
{
public DateTime ADate = DateTime.Now;
public Test ()
{
Test test = new Test();
if (test.ADate == null)
{
Console.WriteLine("What the?");
}
}
}
I guess this is because "==" is a syntax sugar which actually represents call to
System.Object.Equals
method that acceptsSystem.Object
parameter. Null by ECMA specification is a special type which is of course derived fromSystem.Object
.That's why there's only a warning.
The compiler will allow you to compare any struct implementing the
==
to null. It even allows you to compare an int to null (you would get a warning though).But if you disassemble the code you will see that the comparison is being solved when the code is compiled. So, for instance, this code (where
Foo
is a struct implementing==
):Generates this IL:
As you can see:
Is translated to:
Whereas:
Is translated to false:
The fact that a comparison can never be true doesn't mean that it's illegal. Nonetheless, no, a value type can ever be
null
.I think the best answer as to why the compiler accepts this is for generic classes. Consider the following class...
If the compiler didn't accept comparisons against
null
for value types, then it would essentially break this class, having an implicit constraint attached to its type parameter (i.e. it would only work with non-value-based types).[EDITED: made warnings into errors, and made operators explicit about nullable rather than the string hack.]
As per @supercat's clever suggestion in a comment above, the following operator overloads allow you to generate an error about comparisons of your custom value type to null.
By implementing operators that compare to nullable versions of your type, the use of null in a comparison matches the nullable version of the operator , which lets you generate the error via the Obsolete attribute.
Until Microsoft gives us back our compiler warning I'm going with this workaround, thanks @supercat!
I suspect that your particular test is just being optimized out by the compiler when it generates the IL since the test will never be false.
Side Note: It is possible to have a nullable Int32 use Int32? x instead.