Data Structures and Algorithms with Object-Oriented Design Patterns in C#
next up previous contents index

Comparison Operators

Program gif 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.

   program4386
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.


next up previous contents index

Bruno Copyright © 2001 by Bruno R. Preiss, P.Eng. All rights reserved.