Comparing arrays content, difference of SequenceEqual and StructuralComparisons.StructuralEqualityComparer

.net, .net-4.0, c#

Solution

The implementation of `SequenceEqual` is kind of similar::

using (IEnumerator<TSource> enumerator1 = first.GetEnumerator())
using (IEnumerator<TSource> enumerator2 = second.GetEnumerator())
{
    while (enumerator1.MoveNext())
    {
        if (!enumerator2.MoveNext() || !comparer.Equals(enumerator1.Current, enumerator2.Current))
        {
            return false;
        }
    }

    if (enumerator2.MoveNext())
    {
        return false;
    }
}

return true;

This default `SequenceEqual` method use default `EqualityComparer<int>.Default` for `int` which is value equality.

`Array` implement `IStructuralEquatable` with `Equal` method:

bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
    if (other == null) return false;

    if (!object.ReferenceEquals(this, other))
    {
        Array array = other as Array;
        if ((array == null) || (array.Length != this.Length))
        {
            return false;
        }
        for (int i = 0; i < array.Length; i++)
        {
            object x = this.GetValue(i);
            object y = array.GetValue(i);

            if (!comparer.Equals(x, y))
            {
                return false;
            }
        }
    }

    return true;
}

The `IEqualityComparer` from input parameter is used, in here you input `StructruralEqualityComparer` but `int` does not implement `IStructruralEquatable`, so it uses default comparer for `int` which is value equality.

But, needless to input `StructruralEqualityComparer` because `int` is not structural, you should just use:

(arr1 as IStructuralEquatable).Equals(arr2, EqualityComparer<int>.Default);

It still works. You should use `StructruralEqualityComparer` if item in array is structrural

So to sum up, the implementation for both is kind of the same, both iterate two array based on value equality of `int` to make comparison.

I would prefer the LINQ verson since it is more readable.

Problem

I have 2 arrays : ``` int[] arr1 = new int[] { 1, 2, 3 }; int[] arr2 = new int[] { 1, 2, 3 }; ``` I need to check if they are equal ( not by ref) What is the difference between writing : ``` Console.WriteLine(arr1.SequenceEqual(arr2)); //true ``` vs ``` IStructuralEquatable eqArray1 = arr1; Console.WriteLine(eqArray1.Equals(arr2, StructuralComparisons.StructuralEqualityComparer)); //true ``` both returns True.. When should I use each ?

Original source