Equality and Equivalence

Note: This is related to a twitter conversation that started iwth Jared Parsons here. I felt this was worth more than 140 characters.

Let’s pose Jared’s original question:

“Should IEquatable<T>.Equals and IComparable<T>.CompareTo always agree on equality?”

I continue to assert “Not always”.  IComparable<T> determines if two objects are equivalent based on the sorting order. IEquatable<T> determines if they are equal.

The example I gave on twitter was a Person class: Two people may have the same name, and yet not be equal. Some people disagreed with me, saying that it would be better to provide different sort order via different IComparer implementations, and leave equality to match all observable properties on an object.

It’s true that in many applications, two objects that compare as equivalent using IComparable<T>.CompareTo() will compare as equal using IEquatable<T>.Equals().

It should also always be true that if two objects are considered equal by calling IEquatable<T>.Equals(), they must be equivalent as seen by IComparable<T>.CompareTo().

However, there will continue to be examples where two objects are equivalent (as determined by IComparable<T>.CompareTo(), but not equal (as determined by IEquatable<T>.Equals().)

Let’s consider a larger example. Here I have a Star class, from an Astronomy based application:

 

// Ordered from coolest to hotest, so the natural order in an enum
// would go from coolest to hotest.
public enum SpectralScale
{
    T,
    L,
    M,
    K,
    G,
    F,
    A,
    B,
    O
}
public class Star : IComparable<Star>, IEquatable<Star>
{
    public SpectralScale SpectralType { get; set; }
    public int SpectralHeat { get; set; }

    // Usually displayed using Roman Numerals from I thru V
    public int LuminosityClass { get; set; }
    public string Name { get; set; }

    public override string ToString() => $"{SpectralType}{SpectralHeat}{ToRoman(LuminosityClass)}";

    private string ToRoman(int luminosityClass)
    {
        string[] numerals = { "", "I", "II", "III", "IV", "V" };
        return numerals[luminosityClass];
    }

    public int CompareTo(Star other)
    {
        int typeCompare = this.SpectralType.CompareTo(other.SpectralType);
        if (typeCompare != 0)
            return typeCompare;
        int heatCompare = this.SpectralHeat.CompareTo(other.SpectralHeat);
        if (heatCompare != 0)
            return heatCompare;
        return this.LuminosityClass.CompareTo(other.LuminosityClass);
    }

    public bool Equals(Star other)
    {
        return ((this.CompareTo(other) == 0) &&
            this.Name == other.Name);
    }
}

 

In this application, stars are classified using the Morgran-Keenan (MK) system. You can read more here. In this classification, stars are classified using the heat generated, and their luminosity. In this classification system, many stars may have equivalent classifications (the sun’s value is G2V). However, the stars with the same value are not the equal; they are different stars.

You can see this in the implementation of Equals: It checks CompareTo, and then adds an additional comparison.

To reiterate: Stars with the same classification are equivalent. They may not be equal. (They are only equal if the object references refer to the same star in the sky).

You will find many examples of this behavior in many fields: a circle and a square may be equivalent (based on their area), but they are not equal. We may sort contestants in a sporting event by points: ties don’t imply equality.

Equivalence may not mean Equality

So many of the real world code we write contains classes where equivalence and equality are the same in practice that we forget that this is not a universal truth. Write the code you mean. And be careful about assumptions.

Tags: C#
Created: 2/16/2016 10:22:58 PM

Current Projects

I create content for .NET Core. My work appears in the .NET Core documentation site. I'm primarily responsible for the section that will help you learn C#.

All of these projects are Open Source (using the Creative Commons license for content, and the MIT license for code). If you would like to contribute, visit our GitHub Repository. Or, if you have questions, comments, or ideas for improvement, please create an issue for us.

I'm also the president of Humanitarian Toolbox. We build Open Source software that supports Humanitarian Disaster Relief efforts. We'd appreciate any help you can give to our projects. Look at our GitHub home page to see a list of our current projects. See what interests you, and dive in.

Or, if you have a group of volunteers, talk to us about hosting a codeathon event.