Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Legitimate uses of ReferenceEquals()

In a .NET program that's written to follow declarative style, what are some legitimate uses for ReferenceEquals()?

like image 766
GregC Avatar asked Mar 28 '12 15:03

GregC


People also ask

What is ReferenceEquals?

ReferenceEquals() Method is used to determine whether the specified Object instances are the same instance or not. This method cannot be overridden.

What is the most accurate way to check for equality by reference?

To check for reference equality, use ReferenceEquals. To check for value equality, use Equals or Equals.

What is difference between == and Equals in C#?

The Equality Operator ( ==) is the comparison operator and the Equals() method in C# is used to compare the content of a string. The Equals() method compares only content.


3 Answers

Not sure what you mean by "written to follow declarative style", but ReferenceEquals is usually used when overriding the == operator. From http://msdn.microsoft.com/en-us/library/ms173147.aspx:

public static bool operator ==(ThreeDPoint a, ThreeDPoint b)
{
    // If both are null, or both are same instance, return true.
    if (System.Object.ReferenceEquals(a, b))
    {
        return true;
    }

    // If one is null, but not both, return false.
    if (((object)a == null) || ((object)b == null))
    {
        return false;
    }

    // Return true if the fields match:
    return a.x == b.x && a.y == b.y && a.z == b.z;
}

It is important to see the Note below for the justification:

Note: A common error in overloads of operator == is to use (a == b), (a == null), or (b == null) to check for reference equality. This instead creates a call to the overloaded operator ==, causing an infinite loop. Use ReferenceEquals or cast the type to Object, to avoid the loop.

like image 118
Chris Shain Avatar answered Oct 05 '22 05:10

Chris Shain


In a .NET program that's written to follow declarative style, what are some legitimate uses for ReferenceEquals()?

There is only one legitimate use of ReferenceEquals regardless of the "style" in which the program is written: to compare two references for reference equality.

If you are using ReferenceEquals for something other than comparing two references for reference equality, you're probably doing something wrong.

like image 33
Eric Lippert Avatar answered Oct 05 '22 06:10

Eric Lippert


Well, if the design and/or usage of the related objects is such that there is never more than one instance of any object that is "equal" to any other, then it will be correct, and it's likely to be quicker than comparing some number of instance variables.

Or, as posted in another answer, you can check it first as an "easy out" and only perform a deep equals check if they are different. This usage it just a performance improvement.

like image 21
Servy Avatar answered Oct 05 '22 07:10

Servy