0

Possible Duplicate:
What's the difference between IEquatable and just overriding Object.Equals() ?

I know that all classes in C# are deived from object and object has a virtual method named Equals().

Why should I impliment IEquatable? Why not to override object.Equals?

Community
  • 1
  • 1
mans
  • 17,104
  • 45
  • 172
  • 321
  • 2
    Same as [What's the difference between IEquatable and just overriding Object.Equals() ?](http://stackoverflow.com/questions/2734914/whats-the-difference-between-iequatable-and-just-overriding-object-equals). – Matthew Flaschen Mar 25 '11 at 14:28

1 Answers1

3

IEquatable<T> defines

bool Equals(T other)

While object's Equals defines

bool Equals(object other)

So defining IEquatable for your class allows you to do an easier comparison of two items of the same class without having to cast to the current type. A lot of times you'll see people implement IEquatable and then override object's Equals to call IEquatable's equals:

public class SomeClass : IEquatable<SomeClass>
{
    public bool Equals(SomeClass other)
    {
        // actual compare
    }

    public override bool Equals(object other)
    {
        // cross-call to IEquatable's equals.
        return Equals(other as SomeClass); 
    }
}

In addition, you can define equality between other types as well. Like make Fraction implement IEquatable

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
James Michael Hare
  • 37,767
  • 9
  • 73
  • 83
  • @Andrew: Hah, another Hare? Wonder if we're related anywhere in our ancestry... – James Michael Hare Mar 25 '11 at 15:42
  • Very cool! My middle name is Michael as well - small world :) – Andrew Hare Mar 27 '11 at 00:14
  • 1
    Applying IEquatable to structures is a big win, since it allows them to be compared without boxing. Applying IEquatable to *sealed* immutable reference types is a small win since it eliminates the need for type-checking and/or type-casting. Applying it to unsealed types is dangerous, because a derived type which overrides Object.Equals without overriding IEquatable will expose different equality-test methods to different consumers. That might not be a horrible thing if IEquatable included its own GetHashCode, but it doesn't. – supercat Sep 13 '11 at 19:48
  • And you both are separated by exactly 100k :) – nawfal Dec 04 '12 at 17:21