#418 – Implementing the IComparable Interface

If you implement a reference type where it makes sense to compare two instances of the type, with one instance greater or lesser than another, you should implement the IComparable interface for your type.  IComparable is used within .NET when sorting elements of a list, e.g. List<T>.Sort.

Here’s an example for a Rectangle type.

        // 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 (this.Equals(r))
                return 0;

            else if (this.Area() == r.Area())
                return this.Width - r.Width;

            else
                return this.Area() - r.Area();
        }

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment