Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can .NET test arrays for equivalence and 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'm looking for a way to compare arrays which would compare the internal values instead of refernces. Is there a built in way to do this in .NET?

Also, while I understand Equals comparing references, GetHashCode returns different values for these two arrays also, which I feel shouldn't happen, since they have the same internal values.

like image 659
dlras2 Avatar asked Apr 28 '11 03:04

dlras2


1 Answers

I believe 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

As far as the issue with GetHashCode returning different values, remember that you are dealing with two distinct values here. You are not comparing arrays, you are comparing two references to arrays.

Default equality comparison for reference types needs to be consistent. If you need something else to happen remember there is a built in model for that using IEqualityComparer<T> which allows you to define custom equality comparison based on specific needs that don't follow the standard reference equality pattern.

like image 80
Josh Avatar answered Sep 18 '22 10:09

Josh