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
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.
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)
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With