Value Types and Null

Anyone has any idea of what is going on with value type comparisons against null in the Microsoft C# 2.0 compiler (and also the Orcas compiler exhibits this problem):

The compiler allows code like this:

	DateTime dt = DateTime.Now;   // this is a value type

	// Compare value type to null, invalid in CSC 1:
	if (dt != null){
		// ...
	}
	

The problem is that the above is always known to be false (dt can not be null), so CSC generates generates the equivalent to "if (true)" every single time (it becomes a no-op).

Adding support for this to the Mono compiler is simple enough but this sounds wrong. Because those testing a value type against null are doing a pointless test and they might be under the mistaken impression that the test is guarding them from an invalid state which it is not.

A few folks have reported this, but I can not find any rationale for this in the ECMA spec, it sounds like a bug in Microsoft's compiler related to the nullable-type support in their compiler.

Posted on 13 Mar 2007 by Miguel de Icaza
This is a personal web page. Things said here do not represent the position of my employer.