ReferenceEquals(variable, null) is the same as variable == null?

本小妞迷上赌 提交于 2021-02-09 11:58:08

问题


Basically the title. I see a lot of the former in the code I'm working on and I was wondering why they didn't use the latter. Are there any differences between the two?

Thanks.


回答1:


Straight from the documentation

Unlike the Equals method and the equality operator, the ReferenceEquals method cannot be overridden. Because of this, if you want to test two object references for equality and are unsure about the implementation of the Equals method, you can call the ReferenceEquals method. However, note that if objA and objB are value types, they are boxed before they are passed to the ReferenceEquals method.




回答2:


Not really. One can overload operator ==, so you basically can get it return e.g. false always. The recommended usage for this operator is to signify value equality, so (for correcftly implemented operator) basically check against null may return true if the object is semantically null.

See this article for more details and some historical overview.

Another difference is that for value types ReferenceEquals doesn't make much sense: for example, any two "instances" of int 0 have to be considered the same in any sane circumstances. (For purists: I put quotes because, strictly speaking, we cannot talk about instances of a value type.)




回答3:


The main benefit of ReferenceEquals() is that the intention is much clearer, you are trying to determine if two references are equal, not if the contents of the objects referred to are equal.

It does this by checking for operator == equality between the two references cast to object (since the params are both object), which eliminates any subclass operator == overloads that might confuse the issue (like string's).

So essentially, this:

if (ReferenceEquals(x, y))

Is the same as this:

if (((object)x) == ((object)y))

Though the former is easier to read.

There are definitely times where it comes in handy, especially avoiding infinite recursion when you are overloading operator == yourself:

public class Foo
{
    public static bool operator ==(Foo first, Foo second) 
    {
        // can't say if (first == second) here or infinite recursion...
        if (ReferenceEquals(first, second))
        {
            // if same object, obviously same...
            return true;
        }

        // etc.
    }
 }


来源:https://stackoverflow.com/questions/12918197/referenceequalsvariable-null-is-the-same-as-variable-null

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