In C#
, why Equals()
method always check equality between two arrays
by comparing the references the and not by comparing the content ?
As a consequence, all methods calling Equals()
in their implementation (a lot) does not work as expected with arrays (it does not compare the content) :
Example :
int[] array1 = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] array2 = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9};
var u = array1.Equals(array1); //true
var v = array1.Equals(array2); //false
var w = Array.Equals(array1, array2); //false
var x = (new List<int[]>(new int[][] { array1 })).Contains(array2); //false
var y = (new int[][] { array1 }).Any(x => x == array2); //false
var z = (new int[][] { array1, array2 }).Distinct().Count() == 1; //false
A possible generic way to handle arrays (no mater the type) could be :
In Object.Equals()
: if both types to compare are arrays (of same length), enumerate items (always possible), for each item, call Equals()
. If one of these calls return false
, array are different (return false
) otherwise return true
.
Note : I know about SequenceEqual()
, memcmp()
and other ways to compare two arrays. My question is not about how to compare arrays. I just want to know why C#
designers dont choose to implement a full array comparaison in Equals()
method.