I have a co-worker who's a fan of writing his null checks as follows:
if (!ReferenceEquals(myObject, null))
I, on the other hand, find this syntax cumbersome to read and prefer:
if (myObject != null)
I've found some articles and stack overflow questions discussing the merits of ReferenceEquals with respect to operator overloading, but outside of the operator overloading scenario, is there any benefit to ReferenceEquals vs == ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With