Compare two objects by reference when the equality operator is redefined

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

+7
c #
source share
2 answers

Operators cannot be overridden - they can be overloaded.

Thus, the == operator in object.ReferenceEquals still compares the links, or you can do the same yourself by exposing 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 
+7
source share

ReferenceEquals does exactly what you need if you are not talking about a dictionary. It does not check Equals (it is literally just ldarg.0 , ldarg.1 , ceq , ret ). Alternatively, just reset the object:

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

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

+5
source share

All Articles