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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With