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 == ?
With c# 7, you can use:
It's equivalent to
Really, really late reply - but I hit the article when I was reading the EFCore library and came across this method...
There is a Check class in Microsoft.EntityFrameworkCore.Utilities that uses this logic for a null check....
So, I wanted to chime in on this conversation even though it's a million years old.
Lets's say we want to write an extension method that checks for null. We could do the following:
but this code is boring.
The reason why is that T has to be a class. Why? Because we can't compare value types with null. Which makes writing decent generic code a big pain.
Alternatively you can attach the same method to object and never care what that object is.
This opens other possibilities like of writing fault tolerant monads for Linq for example or what have you - without actually constraining your generic code.
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;
orreturn false;
. Additionally, if there is an overloaded operator there's a decent chance that it won't perform as well asReferenceEquals
(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.As explained in the other answers, the semantic of the two calls is a little different.
In case you want to use the semantic of
ReferenceEquals
but with simplified syntax, for reference types you can also use: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 againstnull
, 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, notReferenceEquals
.