On this page on MSDN they describe the SequenceEqual
method of the Enumerable
class.
Halfway down the page it states:
If you want to compare the actual data of the objects in the sequences instead of just comparing their references, you have to implement the IEqualityComparer generic interface in your class. The following code example shows how to implement this interface in a custom data type and provide GetHashCode and Equals methods.
Then they show an example where they do not implement the IEqualityComparer<T>
interface at all but instead implement IEquatable<T>
. I've done the test myself without implementing either IEqualityComparer or IEquatable and simply overriding Object's Equals and I find it does the trick. Here is the sample:
class AlwaysEquals
{
override public bool Equals(Object o)
{
return true;
}
public override int GetHashCode()
{
return 1;
}
}
Note here that my class AlwaysEquals implements nothing, no IEquatable, no IEqualityComparer, nothing. However when I run this code:
AlwaysEquals ae1 = new AlwaysEquals();
AlwaysEquals ae2 = new AlwaysEquals();
AlwaysEquals ae3 = new AlwaysEquals();
AlwaysEquals[] Ae1 = new AlwaysEquals[] {ae3, ae2, ae3};
AlwaysEquals[] Ae2 = new AlwaysEquals[] {ae1, ae1, ae1};
Console.WriteLine(Ae1.SequenceEqual(Ae2));
.. I get True
and not False
as I would expect from reading the documentation. How does this actually work?