Search code examples
c#iequatable

When To Use IEquatable<T> And Why


What does IEquatable<T> buy you, exactly? The only reason I can see it being useful is when creating a generic type and forcing users to implement and write a good equals method.

What am I missing?


Solution

  • From the MSDN:

    The IEquatable(T) interface is used by generic collection objects such as Dictionary(TKey, TValue), List(T), and LinkedList(T) when testing for equality in such methods as Contains, IndexOf, LastIndexOf, and Remove.

    The IEquatable<T> implementation will require one less cast for these classes and as a result will be slightly faster than the standard object.Equals method that would be used otherwise. As an example see the different implementation of the two methods:

    public bool Equals(T other) 
    {
      if (other == null) 
         return false;
    
      return (this.Id == other.Id);
    }
    
    public override bool Equals(Object obj)
    {
      if (obj == null) 
         return false;
    
      T tObj = obj as T;  // The extra cast
      if (tObj == null)
         return false;
      else   
         return this.Id == tObj.Id;
    }