Is “ReferenceEquals(myObject, null)” better practi

2020-05-29 13:22发布

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# .net vb.net
9条回答
Evening l夕情丶
2楼-- · 2020-05-29 13:26

With c# 7, you can use:

if ( !(myObject is null) )

It's equivalent to

if (!ReferenceEquals(myObject, null))
查看更多
Rolldiameter
3楼-- · 2020-05-29 13:29

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;
        }
查看更多
做个烂人
4楼-- · 2020-05-29 13:30

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.

查看更多
冷血范
5楼-- · 2020-05-29 13:32

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.

查看更多
走好不送
6楼-- · 2020-05-29 13:33

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)
查看更多
唯我独甜
7楼-- · 2020-05-29 13:40

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.

查看更多
登录 后发表回答