Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "ReferenceEquals(myObject, null)" better practice than "myObject == null"?

Tags:

c#

.net

vb.net

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 == ?

like image 729
mdryden Avatar asked Sep 17 '12 19:09

mdryden


3 Answers

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.

like image 103
Reed Copsey Avatar answered Oct 16 '22 06:10

Reed Copsey


With c# 7, you can use:

if ( !(myObject is null) )

It's equivalent to

if (!ReferenceEquals(myObject, null))
like image 36
BernardV Avatar answered Oct 16 '22 07:10

BernardV


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.

like image 5
Servy Avatar answered Oct 16 '22 07:10

Servy