简体   繁体   中英

Is this way of using ReferenceEquals correct

I am doing some code review and I stopped on the following construct. Is this the Correct way of using ReferenceEquals to check if a method returned actually the same object that was passed as an argument or a new one?

int x = 5;
Foo f = new Foo()

Foo DoSomething(Foo f)
{
    if(x > 5)
    {
         return f;
    }
    else
    {
        return new Foo();
    }
}

Foo ff = DoSomething(f);

if(Object.ReferenceEquals(ff, f))
{
    //do something
}

Yes for reference types. Value types bit complicated as they are boxed before passing to the method.

When comparing value types. If objA and objB are value types, they are boxed before they are passed to the ReferenceEquals method. This means that if both objA and objB represent the same instance of a value type, the ReferenceEquals method nevertheless returns false,

Read more details here

Reference equality of value types

ReferenceEquals Method - MSDN

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM