Override Relational Operators When You Implement IComparable

When a class implements IComparable, it must implement the CompareTo method.  For completeness, you should also override the relational operators.
Here’s an example.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
public class Rectangle : IEquatable<Rectangle>, IComparable<Rectangle>
{
    public int Height { get; set; }
    public int Width { get; set; }
 
    public Rectangle(int height, int width)
    {
        Height = height;
        Width = width;
    }
 
    public override bool Equals(object obj)
    {
        return this.Equals(obj as Rectangle);
    }
 
    public override int GetHashCode()
    {
        return Height.GetHashCode() ^ Width.GetHashCode();
    }
 
    public bool Equals(Rectangle r)
    {
        if (ReferenceEquals(r,null))
            return false;
 
        return ((Height == r.Height) && (Width == r.Width) ||
                (Height == r.Width) && (Width == r.Height));
    }
 
    public static bool operator ==(Rectangle r1, Rectangle r2)
    {
        if (ReferenceEquals(r1, null))
        {
            return ReferenceEquals(r2, null) ? true : false;
        }
 
        return r1.Equals(r2);
    }
 
    public static bool operator !=(Rectangle r1, Rectangle r2)
    {
        return !(r1 == r2);
    }
 
    // Result:
    //  < 0 : this instance less than r
    //  = 0 : this instance equivalent to r
    //  > 0 : this instance greater than r
    public int CompareTo(Rectangle r)
    {
        if (ReferenceEquals(r, null))
            return 1; 
 
        if (this.Equals(r))
            return 0;
 
        else if (this.Area() == r.Area())
            return this.Width - r.Width;
 
        else
            return this.Area() - r.Area();
    }
 
    public static bool operator <(Rectangle r1, Rectangle r2)
    {
        if (ReferenceEquals(r1, null))
            return false;
 
        else
            return (r1.CompareTo(r2) < 0) ? true : false;
    }
 
    public static bool operator >(Rectangle r1, Rectangle r2)
    {
        if (ReferenceEquals(r1, null))
            return false;
 
        else
            return (r1.CompareTo(r2) > 0) ? true : false;
    }
 
    public static bool operator <=(Rectangle r1, Rectangle r2)
    {
        return (r1 < r2) || (r1 == r2);
    }
 
    public static bool operator >=(Rectangle r1, Rectangle r2)
    {
        return (r1 > r2) || (r1 == r2);
    }
 
    public int Area()
    {
        return Height * Width;
    }
}