Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEqualityComparer vs EqualityComparer?

I've read this post but it doesn't answer my question.

MSDN says:

We recommend that you derive from the EqualityComparer(Of T) class instead of implementing the IEqualityComparer(Of T) interface, because the EqualityComparer(Of T) class tests for equality using the IEquatable(Of T).Equals method instead of the Object.Equals method.

but if I look at the implementation, they both use the generic Type:

 public class AAA:IEqualityComparer<Box>
    {
        public bool Equals(Box x, Box y)
        {
        }

        public int GetHashCode(Box obj)
        {
        }
    }

    public class BBB : EqualityComparer<Box>
    {
        public override bool Equals(Box x, Box y)
        {
        }

        public override int GetHashCode(Box obj)
        {
        }
    }

What am I missing?

like image 584
Royi Namir Avatar asked Mar 04 '12 21:03

Royi Namir


People also ask

What is equalitycomparer?

Alt+Insert | Equality Comparer ( ReSharper_GenerateEqualityComparer ) IEqualityComparer<T> is a generic . NET interface that allows implementing customized equality comparison for collections. Creating a comparer class for your type is an alternative to creating Equals() and GetHashCode() methods for the type.

What collection would use an IEqualityComparer T to enforce uniqueness?

Methods in HashSet Collection This method copies the elements of a HashSet<T> object to an array. This method returns an IEqualityComparer object. this object can be used for the equality testing of a HashSet<T> object.

What is IEquatable?

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 . It should be implemented for any object that might be stored in a generic collection.


1 Answers

I think the other post you mention is saying that EqualityComparer<Box> implements IEqualityComparer<Box> and IEqualityComparer, so you don't have to implement both the generic and non-generic interfaces if you derive from EqualityComparer<Box>.

like image 153
phatraven Avatar answered Sep 22 '22 13:09

phatraven