Sebastian Widz
Sebastian Widz

Reputation: 2072

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
}

Upvotes: 1

Views: 91

Answers (2)

CharithJ
CharithJ

Reputation: 47510

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

Upvotes: 1

Oleksiy Dymashok
Oleksiy Dymashok

Reputation: 319

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.

Upvotes: 0

Related Questions