#405 – Equals Method for Equivalence, == Operator for Identity
September 6, 2011 Leave a comment
You can check for equality between two objects by calling the Equals method or by using the == operator. There are some differences between how the methods work, but both Equals and == can be overloaded in a user-defined type.
You can therefore change the behavior of one of these methods, or both. The question is–how should these two behaviors work for a custom class?
Roughly speaking, the desired behavior, from a client’s point of view is:
- Use Equals method to determine value equality, or equivalence–do the two objects represent the same thing?
- Use == operator to determine reference equality, or identity–do the two references point to exactly the same object?
This argues for overloading Equals for a user-defined reference type, but not overloading the == operator.
This would result in the following behavior:
Dog d1 = new Dog("Lassie", 7); Dog d2 = new Dog("Lassie", 7); bool bValueEquality = d1.Equals(d2); // true bool bRefEquality = d1 == d2; // false