[Mono-devel-list] Comparing against null

Jonathan Gilbert 2a5gjx302 at sneakemail.com
Sat Apr 9 10:47:13 EDT 2005

At 11:00 AM 09/04/2005 +0200, Michal Moskal wrote:
>On Apr 9, 2005 1:07 AM, Jonathan Gilbert <2a5gjx302 at sneakemail.com> wrote:
>> :-), simply because nobody has mentioned it yet, that there IS an official
>> way to always do a reference check: ReferenceEquals(a, b). I do not know if
>> the JIT recognizes when this compares against null and simplifies it to
>> brtrue/brfalse, but it seems like an obvious -- and simple -- thing to do
>> (just need to be careful that the user hasn't created their own 'new'
>> static ReferenceEquals function).
>Well, there is an easier way, which is clearly optimized:
>  (object)foo == (object)bar

Whether this is easier in a matter of opinion :-) Firstly, it is actually 1
byte longer than calling ReferenceEquals (unless you put a space after the
function name, in which case the length is the same). Secondly, and more
importantly, it is immediately evident to the casual reader what
ReferenceEquals(a, b) means. It requires knowledge of the language in
sufficient depth to realize that overloaded operators are typed at
compile-time and that 'object' does not overload its '==' operator.

Also, even knowing this, it isn't obvious that either of
Object::ReferenceEquals and Object::operator== will be optimized when
comparing against null. It is probable, of course, but it isn't required by
the language specification.

There is no reason to not optimize both :-) ReferenceEquals exists
precisely to bypass the overloaded operator, and probably a good fraction
of the time, it's because people don't want to pass 'null' into
operator==(). (Whether they should or shouldn't be is a different matter
altogether :-)

The bottom line is, I tend to write my code for readability, and I find:

if (ReferenceEquals(a, null))

..more readable than:

if (null != (object)a)


Jonathan Gilbert

More information about the Mono-devel-list mailing list