Use IComparable Fields and Properties

Problem
You want to know how to leverage IComparable or IComparer when comparing objects on their date/time, numeric, or string elements.

Solution
If possible, delegate to the IComparable or IComparer interface that’s exposed by an object’s inner fields and properties.

Example

public class Account : IComparable {
    // Make this a property in a real-world class.
    public int AccountNumber;

    // Compare Account instances on their AccountNumber.
    public int CompareTo(object obj) {
        // Throw if other object can't be cast to Account.
        Account other = (Account) obj;

        // Any Account is greater than a null object.
        if ( other == null ) {
            return 1;
        }
        else {
            // Build on the IComparable interface for strings.
            return this.AccountNumber.CompareTo(other.AccountNumber);
        }
    }
}

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