Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two objects by reference when equality operator is overridden

Tags:

c#

.net

I need to check if two objects of the same type are the same instances and point to the same allocation of memory. The problem is that the type has overloaded equality operator and thus it will use it as comparing the both for equality, but I need to check them for reference. I looked through object.ReferenceEquals() method, but it internally applies equality operator

like image 547
Nick Reshetinsky Avatar asked Jul 05 '17 11:07

Nick Reshetinsky


People also ask

Is it safe to use the equality operators to compare reference types?

Most reference types should not overload the equality operator, even if they override Equals. However, if you are implementing a reference type that is intended to have value semantics, such as a complex number type, you should override the equality operator.

How do you compare two objects using the equal method?

The equals() method of the Object class compare the equality of two objects. The two objects will be equal if they share the same memory address. Syntax: public boolean equals(Object obj)

Does == compare reference?

For example, in Java, comparing objects using == usually produces deceptive results, since the == operator compares object references rather than values; often, this means that using == for strings is actually comparing the strings' references, not their values.

Which is used to check the reference equality?

As a general rule, use the Object. equals() method to check whether two objects have equivalent contents and use the equality operators == and != to test whether two references specifically refer to the same object. This latter test is referred to as referential equality.


2 Answers

Operators can't be overridden - they can only be overloaded.

So the == operator in object.ReferenceEquals is still comparing references, or you could do the same thing yourself by casting one or both operands:

string x = "some value";
string y = new string(x.ToCharArray());
Console.WriteLine(x == y);                   // True
Console.WriteLine((object) x == (object) y); // False
Console.WriteLine(ReferenceEquals(x, y));    // False
like image 181
Jon Skeet Avatar answered Oct 14 '22 01:10

Jon Skeet


ReferenceEquals does exactly what you need, unless you're talking about a dictionary. It does not check Equals (it literally just does ldarg.0, ldarg.1, ceq, ret). Alternatively, just cast to object:

bool same = (object)x == (object)y;

If you need dictionary support (so: GetHashCode): System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj) is your friend.

like image 26
Marc Gravell Avatar answered Oct 14 '22 02:10

Marc Gravell