Tuesday, September 21, 2010

Equals vs Equals

Could you create an example, when System.Object.Equals(a,b) will return true and a.Equals(b)will return false


And moreover, why does your example works and what paradigm have you violated to achieve the result?

The answer could be rather simple, but sometimes (again, for value types) it is kinda weird.

To find the answer, let's go down to  Object.Equals(a,b) implementation:
public static bool Equals(object objA, object objB)
{
  return ((objA == objB) || (((objA != null) && (objB != null)) && objA.Equals(objB)));
}


The operator == is defined as ReferenceEqual(), so reference typed object before any comparison would be compared by reference. So the simplest answer is to override Equals() method to always return false.

There is three simple paradigm for the Equals() method:
  1. a.Equals(b) == b.Equals(a)
  2. a.Equals(a) == true
  3. If a.Equals(b) and b.Equals(c), then a.Equals(c)
In this case we're violating the second paradigm.

No comments:

Post a Comment