Information Technology Reference
In-Depth Information
ment match the B members of the left-side argument, B.Equals() consid-
ers the objects equal. Even though the two objects are different types, your
method has considered them equal. You've broken the symmetric property
of Equals. This construct broke because of the automatic conversions that
take place up and down the inheritance hierarchy.
When you write this, the D object is explicitly converted to a B:
baseObject.Equals(derived)
If baseObject.Equals() determines that the fields defined in its type match,
the two objects are equal. On the other hand, when you write this, the B
object cannot be converted to a D object:
derivedObject.Equals(base)
The derivedObject.Equals() method always returns false. If you don't
check the object types exactly, you can easily get into this situation, in
which the order of the comparison matters.
All of the examples above also showed another important practice when
you override Equals(). Overriding Equals() means that your type should
implement IEquatable<T>. IEquatable<T> contains one method:
Equals(T other). Implemented IEquatable<T> means that your type also
supports a type-safe equality comparison. If you consider that the Equals()
should return true only in the case where the right-hand side of the equa-
tion is of the same type as the left side, IEquatable<T> simply lets the com-
piler catch numerous occasions where the two objects would be not equal.
There is another practice to follow when you override Equals(). You should
call the base class only if the base version is not provided by System.Object
or System.ValueType. The previous code provides an example. Class D
calls the Equals() method defined in its base class, Class B. However, Class
B does not call baseObject.Equals(). It calls the version defined in
System.Object, which returns true only when the two arguments refer to
the same object. That's not what you want, or you wouldn't have written
your own method in the first place.
The rule is to override Equals() whenever you create a value type, and to
override Equals() on reference types when you do not want your reference
type to obey reference semantics, as defined by System.Object. When you
write your own Equals(), follow the implementation just outlined. Overrid-
ing Equals() means that you should write an override for GetHashCode().
See Item 7 for details.
 
Search WWH ::




Custom Search