The IComparable Interface

Problem
You want to know when to implement the IComparable interface.

Solution
Implement the IComparable interface if you can compare instances of a type to each other.

Comments
If possible, make the CompareTo method public, and always account for null arguments.

Example

class Triangle : IComparable {
    // In a real class, this would be a property.
    public double Side;

    // Compare triangles by their side property.
    public int CompareTo(object obj) {
        // Throw if other object can't be cast to Triangle.
        Triangle other = (Triangle) obj;

        // Any triangle is greater than a null triangle.
        if ( other == null || this.Side > other.Side ) {
            return 1;
        }
        else if ( this.Side < other.Side ) {
            return -1;
        }
        else {
            return 0;
        }
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s