Question: Will C# 2.0 offer a way to directly and reliably produce the
fastest MSIL null check, i.e. a single opcode?
The current C# compiler will emit this opcode automatically when
comparing a type against null that doesn't override operator==.
However, if the type does have its own equality operator that method
is called instead, which is of course much slower.
Since only a psychotic implementation of operator== would return a
different result for null checks than the default implementation, a
useful workaround to get fast code is to write ((object) obj == null).
Now I'm reading through the C# 2.0 specs and I see a problem. Inside a
template class or method, you can use (obj == null) if obj is of a
generic type. But obj might be a value type! The C# compiler will
support this special case but that means we can't use the (object)
cast anymore.
So what's the deal? Is there another way to check for null -- can we
perhaps call HasValue on arbitrary objects? Or is the C# compiler
going to be revised so that all "== null" and "!= null" expressions
are automatically mapped to the appropriate MSIL opcodes, even in the
presence of user-defined operators? That would be the best solution
IMO, as it would also simplify these operator methods.
--
http://www.kynosarges.de