Specialization, Extension, and Inheritance
- slide 37 : 40
Overriding the Equals method in a class
It is tricky to do a correct overriding of the virtual
Equals
method in class
Object
Methods in class Object
Equality in C#
Equals in class Object
HashCode in class Object
Cases to deal with when redefining the
Equals
method:
Comparison with
null
(
false
)
Comparison with an object of a different type (
false
)
Comparison with
ReferenceEquals
(
true
)
Comparison of fields in two objects of the same type
Other rules when redefining
Equals
:
Must not lead to errors (no exceptions thrown)
The implemented equality should be
reflexive
,
symmetric
and
transitive
Additional work:
GetHashCode
should also be redefined in accordance with
Equals
If
o1.Equals(o2)
then
o1.GetHashCode() == o2.GetHashCode()
If you overload the
==
operator
Also overload
!=
Make sure that
o1 == o2
and
o1.Equals(o2)
return the same result
Equals and GetHashCode Methods in class BankAccount.