Can .NET arrays test equivalence, not just equal references?

var a = new double[] {1, 2, 3}; var b = new double[] {1, 2, 3}; System.Console.WriteLine(Equals(a, b)); // Returns false 

However, I am looking for a way to compare arrays that will compare internal values ​​instead of references. Is there a built-in way to do this in .NET?

In addition, although I understand Equals link comparison, GetHashCode also returns different values ​​for the two arrays, which in my opinion should not happen, since they have the same internal values.

+6
equals arrays
Apr 28 '11 at 3:00
source share
2 answers

I believe that you are looking for the Enumerable.SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) method.

 var a = new double[] {1, 2, 3}; var b = new double[] {1, 2, 3}; System.Console.WriteLine(a.SequenceEqual(b)); // Returns true 

Regarding the problem with GetHashCode returning different values, remember that here you are dealing with two different values. You are not comparing arrays; you are comparing two references to arrays.

The default equality comparison for reference types must be consistent. If you need something else, remember that there is a built-in model for using IEqualityComparer<T> that allows you to define your own equality comparison based on specific ones that do not match the standard reference equality patterns.

+7
Apr 28 2018-11-11T00:
source share

UPDATE: Fixed code for using the correct comparison method (thanks to @CodesInChaos for pointing this out).

If you are running .NET 4, you can use the IStructuralEquatable interface:

 IStructuralEquatable c = b; Console.WriteLine(c.Equals(a, StructuralComparisons.StructuralEqualityComparer)); 

This question contains more detailed information.

+5
Apr 28 2018-11-11T00:
source share



All Articles