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

C#.Netvb.net

C# Problem Overview


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

C# Solutions


Solution 1 - C#

> 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.

Solution 2 - C#

With c# 7, you can use:

if ( !(myObject is null) )

It's equivalent to

if (!ReferenceEquals(myObject, null))

Solution 3 - C#

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.

Solution 4 - C#

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.

Solution 5 - C#

The VB.NET tag probably shouldn't have been included in this question as it is not otherwise mentioned, but, for completeness, Is is equivalent to Object.ReferenceEquals and so can always be used instead of that call.

Solution 6 - C#

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:

public static bool IsNull<T>(this T value) where T : class, new()
{ 
   return value == null;
}

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.

public static bool IsNull(this object value)
{
   return object.ReferenceEquals(value, null);
}

This opens other possibilities like of writing fault tolerant monads for Linq for example or what have you - without actually constraining your generic code.

Solution 7 - C#

ReferenceEquals might be slightly faster. As mentioned before it makes sure that no overloaded Equals operator is being called. Also ReferenceEquals ensures only one comparison is performed instead of possibly 2 depending on the implementation of the overloaded Equals operator. Although it's very likely that the overloaded operator is using ReferenceEquals itself as the first statement.

I personally do use ReferenceEquals, but only on places where I am really tweaking to squeeze out the last clock cycles (places that are possibly called millions of times per second). Or when I have no control over the type, like in the case of generics. ... But again only when performance is really critical.

Solution 8 - C#

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....

        internal static class Check
    {
        [ContractAnnotation("value:null => halt")]
        public static T NotNull<T>([NoEnumeration] T value, [InvokerParameterName] [NotNull] string parameterName)
        {
#pragma warning disable IDE0041 // Use 'is null' check
            if (ReferenceEquals(value, null))
#pragma warning restore IDE0041 // Use 'is null' check
            {
                NotEmpty(parameterName, nameof(parameterName));

                throw new ArgumentNullException(parameterName);
            }

            return value;
        }

Solution 9 - C#

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:

if (myObject is object)

Solution 10 - C#

With C# 9, you can use if (myObject is not null). The reference states the following safety guarantee:

> When you match an expression against null, the compiler guarantees that no user-overloaded == or != operator is invoked.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmdrydenView Question on Stackoverflow
Solution 1 - C#Reed CopseyView Answer on Stackoverflow
Solution 2 - C#BernardVView Answer on Stackoverflow
Solution 3 - C#ServyView Answer on Stackoverflow
Solution 4 - C#KeithSView Answer on Stackoverflow
Solution 5 - C#Mark HurdView Answer on Stackoverflow
Solution 6 - C#bleepzterView Answer on Stackoverflow
Solution 7 - C#It's me ... AlexView Answer on Stackoverflow
Solution 8 - C#codeputerView Answer on Stackoverflow
Solution 9 - C#Borislav IvanovView Answer on Stackoverflow
Solution 10 - C#user3071284View Answer on Stackoverflow