flockofcode
flockofcode

Reputation: 1819

Enumerable.SequenceEqual<TSource> and EqualityComparer<T>

From MSDN

The SequenceEqual(IEnumerable, IEnumerable) method enumerates the two source sequences in parallel and compares corresponding elements by using the default equality comparer for TSource, Default. The default equality comparer, Default, is used to compare values of the types that implement the IEqualityComparer generic interface.

a) As I understand the above quote, it's implying that EqualityComparer<T>.Default is used to compare elements of types that implement the IEqualityComparer<T>, when in fact Default is used to return a particular implementation of IEqualityComparer<T> that either calls IEquatable<T>.Equals (assuming T is assignable to IEquatable<T> ) or it calls Object.Equals

b) Quote also suggests that TSource must implement IEqualityComparer<T>, which isn't true:

   static void Main(string[] args)
   {
        Test test1 = new Test();
        Test test2 = new Test();

        Test[] list1 = { test1, test2 };
        Test[] list2 = { test1, test2 };

        bool eq = list1.SequenceEqual(list2); //works
   }     

  public class Test { }

So did I misinterpret what the quote is trying to convey or is the quote plain wrong?

thank you

Upvotes: 3

Views: 920

Answers (2)

abatishchev
abatishchev

Reputation: 100288

Not TSource should implement IEqualityComparer

But EqualityComparer<T>.Default implements IEqualityComparer

The default equality comparer, Default, is used to compare values of the types that implement the IEqualityComparer generic interface.

That's too oblivious to be mentioned.

Upvotes: 2

BrokenGlass
BrokenGlass

Reputation: 160912

From MSDN:

The Default property checks whether type T implements the System.IEquatable interface and, if so, returns an EqualityComparer that uses that implementation. Otherwise, it returns an EqualityComparer that uses the overrides of Object.Equals and Object.GetHashCode provided by T.

In your example case it just uses reference equality which is the default equality implementation for reference objects.

Upvotes: 2

Related Questions