Home > Articles > Programming > C#

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Make Types Equatable

Scenario/Problem:

You need to determine if two objects are equal.

Solution:

You should override Object.Equals() and also implement the IEquatable<T> interface.

By default, Equals() on a reference type checks to see if the objects refer to the same location in memory. This may be acceptable in some circumstances, but often, you’ll want to provide your own behavior. With value types, the default behavior is to reflect over each field and do a bit-by-bit comparison. This can have a very negative impact on performance, and in nearly every case you should provide your own implementation of Equals().

struct Vertex3d : IFormattable, IEquatable<Vertex3d>
{
    ...
    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;
        if (obj.GetType() != this.GetType())
            return false;
        return Equals((Vertex3d)obj);
    }

    public bool Equals(Vertex3d other)
    {
        /* If Vertex3d were a reference type you would also need:
         * if ((object)other == null)
         *  return false;
         *
         * if (!base.Equals(other))
         *  return false;
         */

        return this._x == other._x
            && this._y == other._y
            && this._z == other._z;
    }
}

There’s nothing stopping you from also implementing IEquatable<string> (or any other type) on your type—you can define it however you want. Use with caution, however, because this may confuse people who have to use your code.

  • + Share This
  • 🔖 Save To Your Account