[Mono-dev] CS0019 for value type != null

Mike Edenfield kutulu at kutulu.org
Tue Apr 8 17:21:16 EDT 2008


Casey Marshall wrote:

> meaning `valuetype' would never be initialized. It's a little nit-picky,
> since I don't think this results in any real bugs, since the value types
> here are usually simple (e.g., Rectangle, DateTime), but it easily
> could. It almost seems like the buggy gmcs was doing a good service -- I
> don't understand why == and != can be used with null vs. a value type,
> if they always evaluate to false and true.

The behavior you're describing doesn't happen for built-in value types 
that C# knows implicitly, only structure types.  In particular:

If you try to compile this:

public void foo ( int i )
{
   if ( i == null )
   {
     doSomething();
   }
}

you get a warning that the comparison is always true.  If you switch to 
!=, you get two warnings: one that the comparison is always false, and a 
second that doSomething() is unreachable.

However, if you compile this:

public void foo ( DateTime dt )
{
   if ( dt == null )
   {
     doSomething();
   }
}

you get no warning.  I'm not 100% sure what's going on, but I read over 
the C# spec on comparison operators, I can take a guess.  It seems that, 
because DateTime doesn't have an explicit operator== defined for Object, 
the compiler resolved the operation to Object.operator==(Object, Object) 
and upcasts DateTime to the base Object.  With the built-in C# value 
types, the language spec is explicit about which comparisons are valid 
and which are not, but DateTime (and Rectangle and others) are custom 
types, so they do not behave the same.

I'm not arguing that this is the best behavior, but it does seem to 
logically fall out of the way the spec defines the operator resolution 
process.

--Mike


More information about the Mono-devel-list mailing list