Data Structures and Algorithms
with Object-Oriented Design Patterns in C# |
Program shows how the comparison operators ==, !=, <, <=, >=, and > are implemented. All of these methods invoke the Compare method and then interpret the result as needed.
The == and != operators are slightly different to make them more robust and easier to use. Specifically, they do the right thing when either operand of == and != is a null reference.
Program: ComparableObject comparison operators.
The use of polymorphism in the way shown gives the programmer enormous leverage. The fact all objects are derived from the ComparableObject base class, together with the fact that every concrete class must implement an appropriate CompareTo method, ensures that the comparison operators can be used to compare any pair of ComparableObjects and that the comparisons always work as expected.