Is "ReferenceEquals(myObject, null)" better practice than "myObject == null"?
but outside of the operator overloading scenario, is there any benefit to ReferenceEquals vs == ?
No - the only advantage (and I'd argue it's not much of an advantage) to explicitly using Object.ReferenceEquals
would be that it will never use the overloaded operator equals. In the non-overloaded case, the == Operator is defined to "returns true if its two operands refer to the same object" for all "reference types other than string". As such, its equivalent (provided its not overloaded).
I, personally, also favor using the second syntax, and find it more maintainable for null checking. I'd also argue that any overloaded operator==
should also provide proper checking against null
, and in the case where it did not for some reason (which would be odd), there'd likely be a specific rationale behind that decision which would cause you to want to use the overload, not ReferenceEquals
.
With c# 7, you can use:
if ( !(myObject is null) )
It's equivalent to
if (!ReferenceEquals(myObject, null))
Well, if someone were to override the == or != operators they could make them do whatever they wanted. The could even have it do something real mean like return true;
or return false;
. Additionally, if there is an overloaded operator there's a decent chance that it won't perform as well as ReferenceEquals
(not guaranteed, and it's probably not enough to matter, but still).
Having said that, since with any sensible implementation of any overloaded operator this is unlikely to be a problem at all. I personally don't use ReferenceEquals
unless I have a compelling reason to not use the ==
operator for that type or in that particular instance.
In terms of null checks, the two should always return the same results. If a non-null reference ever equals null (even when using the Null Object pattern), regardless of whether ReferenceEquals or the == operator was used, it's a very bad thing. So, in that scenario I would use ==/!=.
I would say that, if the == operator were overloaded, using ReferenceEquals might be slightly faster. The first thing an overloaded == should do is see if the two variables point to the same object, so in the case of an overloaded operator you end up with an extra frame on the call stack. Using ReferenceEquals also guarantees that that's the only check performed.
I would generally also use ==/!= in pretty much any other scenario. The entire idea is that the operator defines "equality"; that is not always referential (in fact, most compound objects should be compared structurally for equality; they're equal if their members are equal). The object, theoretically, knows how best to compare itself to another object, for equality, relative order, etc. and so rather than hardcoding a very specific and possibly incorrect piece of logic, you should use the object-oriented nature of the language to let the object tell you whether it's equal to anything else or not.