Whats the Difference between Object.Equals(obj, null) and obj == null

醉酒当歌 提交于 2019-12-11 01:32:07

问题


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:


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.



来源:https://stackoverflow.com/questions/6993481/whats-the-difference-between-object-equalsobj-null-and-obj-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!