Lecture overview -- Keyboard shortcut: 'u'  Previous page: Practical use of virtual methods in C# -- Keyboard shortcut: 'p'  Next page: Upcasting and downcasting in C# -- Keyboard shortcut: 'n'  Lecture notes - all slides and notes together  slide -- Keyboard shortcut: 't'  Textbook -- Keyboard shortcut: 'v'  Help page about these notes  Alphabetic index  Course home  Page 37 : 40
Object-oriented Programming in C#
Specialization, Extension, and Inheritance
Overriding the Equals method in a class

It is tricky to do a correct overriding of the virtual Equals method 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

/user/normark/oop-csharp-1/sources/c-sharp/bank-account/bank-account-equals/bank-account.csEquals and GetHashCode Methods in class BankAccount.