Jon Colverson
Jon Colverson

Reputation: 3066

Can I compare two arbitrary references in a way that can be used in a CompareTo method?

I'm writing an implementation of IComparable<T>.CompareTo(T) for a struct. I'm doing a member-wise comparison (i.e. d = a.CompareTo(other.a); if (d != 0) { return d; } etc.), but one of the members is of a class (let's call it Y) that doesn't implement IComparable or have any other reasonable way of comparing so I just want to compare the references (in this case I know that all instances of Y are unique). Is there a way of doing that that will yield an int that is suitable for use in a comparison method?

Upvotes: 0

Views: 99

Answers (3)

Jon Colverson
Jon Colverson

Reputation: 3066

Comparing the results of Object.GetHashCode() works well enough for my purposes (I just care about reference equality and it doesn't matter where anything unequal is sorted. I want instances of T that have the same instances of Y as members to be next to each other in the sorted result). My T.CompareTo() uses the following helper:

    static int Compare(object a, object b)
    {
        if (a == null)
        {
            return b == null ? 0 : 1;
        }
        if (b == null)
        {
            return -1;
        }
        return a.GetHashCode().CompareTo(b.GetHashCode());
    }

Upvotes: 0

Anthony Pegram
Anthony Pegram

Reputation: 126804

Your statement that the class

doesn't implement IComparable or have any other reasonable way of comparing

Seems to be contra-indicative of finding

a way of doing that that will yield an int that is suitable for use in a comparison method

If the objects cannot be reasonably compared for ordering, it is best to exclude them from the comparison logic entirely.

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 612844

It's not meaningful to compare references looking for order relationships. It's only meaningful to look for equality.

Upvotes: 3

Related Questions