Whats the Difference between Object.Equals(obj, nu

2019-07-16 07:20发布

Almost every time I want to check object's equality to null I use the normal equality check operation

if (obj == null)

Recently I noticed that I'm using the Object.Equals() more often

if (Object.Equals(obj, null))

and while reading about null checking I fount this Is ReferenceEquals(null, obj) the same thing as null == obj?

if (ReferenceEquals(null, obj))

Whats the difference? and where/when to use each one? plus I found that the last two checks look like the same according to their summary

1条回答
小情绪 Triste *
2楼-- · 2019-07-16 07:38

Object.Equals(x, y) will:

  • Return true if x and y are both null
  • Return false if exactly one of x or y is null
  • Otherwise call either x.Equals(y) or y.Equals(x) - it shouldn't matter which. This means that whatever polymorphic behaviour has been implemented by the execution-time type of the object x or y refers to will be invoked.

ReferenceEquals will not call the polymorphic Equals method. It just compares references for equality. For example:

string x = new StringBuilder("hello").ToString();
string y = new StringBuilder("hello").ToString();
Console.WriteLine(Object.Equals(x, y)); // True
Console.WriteLine(Object.ReferenceEquals(x, y)); // False
Console.WriteLine(x == y); // True due to overloading

Now if you're only checking for nullity, then you don't really want the polymorphic behaviour - just reference equality. So feel free to use ReferenceEquals.

You could also use ==, but that can be overloaded (not overridden) by classes - it is in the case of string, as shown above. The most common case for using ReferenceEquals in my experience is when you're implementing ==:

public bool operator ==(Foo x1, Foo x2)
{
    if (ReferenceEquals(x1, x2))
    {
        return true;
    }
    if (ReferenceEquals(x1, null) || ReferenceEquals(x2, null))
    {
        return false;
    }
    return x1.Equals(x2);
}

Here you really don't want to call the == implementation, because it would recurse forever - you want the very definite reference equality semantics.

查看更多
登录 后发表回答