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?
From the MSDN:
The
IEquatable(T)
interface is used by generic collection objects such asDictionary(TKey, TValue)
,List(T)
, andLinkedList(T)
when testing for equality in such methods asContains
,IndexOf
,LastIndexOf
, andRemove
.
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;
}