Search code examples
c#referenceequals

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
}

Solution

  • 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