0

Let's say I have a custom type like

public class MyType
{
    public string name;
    public int count;

    public MyType(string n, int c)
    {
        name = n;
        count = c;
    }
}

in C# and want to have "intuitive" equality comparision for instances of that object. That is compare by value and not be reference. I am aware that the equality operator == and Object.Equals() default to reference equality. But I'd like two objects of MyType to be equal, if the contents match. The first step would be to override Object.Equals() and operator== with something like:

public override bool Equals(object obj)
{
   MyType t = obj as MyType;
   return (this.name == t.name) && (this.count == t.count);
}

However, there are also interfaces like:

which seem to be used in various scenarios involving comparison.

Do I have to implement all of these interfaces and the operator== and operator!= to make sure that any comparison involving MyType (including use in generic collections like e.g. in List<T>.Contains()) compares by value and not by reference? Or is there some other way I am missing? It seems to me that seven interfaces and two operators are quite a lot to have something simple like value comparison implemented.

3
  • 1
    Instead of IComparer interfaces, I think you were looking for IComparable. But that's really when you are required to pass your object into generic comparers that don't care about the data in the object, but need <, >, ==. I would recommend reading this MSDN article: msdn.microsoft.com/en-us/library/ms173147.aspx
    – TyCobb
    Feb 23, 2017 at 23:51
  • Thanks. I've added IComparable to the list.
    – Striezel
    Feb 23, 2017 at 23:55
  • Could the person who downvoted the question recently please explain the reason for that? Thanks.
    – Striezel
    Jun 24, 2018 at 12:11

3 Answers 3

2

The first step would be to override Object.Equals() and operator== with something like:

No, the first step is to override object.Equals() and GetHashCode(). You must never override one without overriding the other to correspond, or else your class is buggy if used as a key.

Let's look at your Equals()

public override bool Equals(object obj)
{
   MyType t = obj as MyType;
   return (this.name == t.name) && (this.count == t.count);
}

There's a bug here because if obj is null or is not a MyType this will throw a NullReferenceException. Let's fix that:

public override bool Equals(object obj)
{
   MyType t = obj as MyType;
   return t != null && (name == t.name) && (count == t.count);
}

I'd also probably put the count comparison before the name as it is likely to give a faster out if it doesn't match, but then I don't know your use-cases so maybe there are a small number of very common count values in which case that doesn't hold. That's an optimisation matter though, let's fix the bug by giving you a corresponding GetHashCode()

public override int GetHashCode()
{
   return (name?.GetHashCode() ?? 0) ^ count;
}

The minimum requirement is that if a.Equals(b) then it must be true that a.GetHashCode() == b.GetHashCode(). We also ideally want to spread the bits around as much as possible. We achieve the first (vital) part by basing our hash code on the properties that determine equality. The second part is more complicated, but in this case the relatively good quality of string's GetHashCode() means just xor-ing with the remaining integer value will probably be reasonably good. Search the site for more details (including why just xoring is often not a good idea in other cases).

Now, you want == semantics. It's a requirement that if you define == you must define !=, but we can easily define one in terms of the other.:

public static bool operator !=(MyType x, MyType y)
{
    return !(x == y);
}

Now once we've got == done != will go through that. Of course we've already defined equality so we can start with using that:

public static bool operator ==(MyType x, MyType y)
{
    return x.Equals(y);
}

This is buggy though because while it handles y being null fine it throws if x is null. We need to consider that too:

public static bool operator ==(MyType x, MyType y)
{
    if (x == null)
    {
         return y == null;
    }
    return x.Equals(y);
}

Let's consider though that everything must be equal to itself (in fact you will be buggy if that doesn't hold). Since we have to consider the possibility of x == null && y == null let's think about that as an example of the case of (object)x == (object)y. This let's us skip the rest of the testing:

public static bool operator ==(MyType x, MyType y)
{
    if ((object)x == (object)y)
    {
        return true;
    }
    if ((object)x == null)
    {
        return false;
    }
    return x.Equals(y);
}

How much of a benefit this is depends on how likely comparing with self is (it can be more common as a side-effect of various things than you might guess) and how expensive the equality method is (in this case not much, but in a case with more fields to compare it could be considerable).

Okay, we've got the Equals and GetHashCode sorted and we've added a == and != as you wanted them. What would be nice to have is IEqutable<MyType>. This offers a strongly-typed Equals that will be used when available by comparers within dictionaries, hash-sets, etc. So it's a nice to have. This will force us to implement bool Equals(MyType other) which will be much like the override we already did, but without the conversion:

public bool Equals(MyType other)
{
   return other != null && (name == other.name) && (count == other.count);
}

Bonus: Because of how overloading works our == is going to call into this slightly faster method instead of the override that does a cast. We've optimised ==, and by extension !=, without even touching them!

Now if we implement this then we have to implement GetHashCode() which in turn means that we have to implement the object.Equals() override, but we've already done that. We're duplicating here though, so lets re-write the override to use the strongly typed form:

public override bool Equals(object obj)
{
  return Equals(obj as MyType);
}

All done. Putting it together:

public class MyType : IEquatable<MyType>
{
    public string name;
    public int count;

    public MyType(string n, int c)
    {
        name = n;
        count = c;
    }

    public bool Equals(MyType other)
    {
       return other != null && (name == other.name) && (count == other.count);
    }

    public override bool Equals(object obj) => Equals(obj as MyType);

    public override int GetHashCode() => (name?.GetHashCode() ?? 0) ^ count;

    public static bool operator ==(MyType x, MyType y)
    {
        if ((object)x == (object)y)
        {
            return true;
        }

        if ((object)x == null)
        {
            return false;
        }

        return x.Equals(y);
    }

    public static bool operator !=(MyType x, MyType y) => !(x == y);
}

IComparable<T> and IComparable are used if you also want to be able to order your objects; to say one is less than or comes before the other. It isn't needed for equality.

IEqualityComparer<T> and IEqualityComparer are used to override all the above and define equality in some completely different way in another class. The classic example here is that sometimes we want "abc" to be equal to "ABC" and sometimes we don't, so we can't just depend on == or the Equals() methods of the types we've described above as they can only apply one rule. They are generally provided by other classes to the actual class being compared.

Let's say we sometimes want to ignore case in comparing MyType instances. Then we can do:

public class CaseInsensitiveMyTypeEqualityComparer : IEqualityComparer<MyType>
{
    public bool Equals(MyType x, MyType y)
    {
        if ((object)x == (object)y)
        {
            return true;
        }
        if ((object)x == null | (object)y == null)
        {
            return false;
        }
        return x.count == y.count && string.Equals(x.name, y.name, StringComparison.OrdinalIgnoreCase);
    }

    public int GetHashCode(MyType obj)
    {
        if (obj == null)
        {
            return 0;
        }
        return StringComparer.OrdinalIgnoreCase.GetHashCode(obj.name) ^ obj.count;
    }
}

If you used this with say:

var dictionary = new Dictionar<MyType, int>(new CaseInsensitiveMyTypeEqualityComparer());

Then the dictionary would be case-insensitive for its keys. Note that since we defined equality based on case-insensitive comparison of the names we have to base the hash code on a case-insensitive hashing of it too.

If you don't use an IEqualityComparer<MyType> then the dictionary uses EqualityComparer<MyType>.Default which uses your more-efficient IEquatable<MyType> implementation since it can, and would have used the object.Equals override if you didn't have that.

You might guess that IEqualityComparer<T> is relatively less-used than just using the equality defined by a class itself. Also if someone does need it, that person might not be you; one of the great things about it is that we can define them for other people's classes. Still, it's not a concern for your design of your class itself.

0
2

You don't need to implement those interfaces to be able to implement the equality operators. Just override them as desired for the type.

But if you do, you must override Equals(object) and GetHashCode() to ensure proper behavior. You should implement IEquatable<T> because... might as well.

Likewise, for comparisons, override the operators as needed. There's no required interface for them. But if you do, again you should implement IComparable<T> in a manner consistent with the behavior of the operators.

You only really need implementations if IEqualityComparer or IComparer if you need to change the way your objects are compared after it has been implemented.

1

You should just need IEquatable<T>, as well as the two operators. As for the others:

IEqualityComparer and IEqualityComparer<T> are used if you want to make another object that's able to determine equality of other objects.

IComparer and IComparer<T> are used if you want to be able to sort your items (so ability to determine if one is greater than an other, not necessarily the same as equality).

Edit:

Also as Jeff mentions, if you override Equals you should also override GetHashCode().

1
  • The Comparer interfaces can be used if you want a special Equatable/Comparable behaviour for a special case that you do not want to be the default equal/compare logic of the class
    – Sir Rufo
    Feb 23, 2017 at 23:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.