In C#, why Equals() method on arrays only compare their references, not their actual content

Although Microsoft’s Framework classes are unfortunately a bit inconsistent with regard to what Object.Equals(Object) means, in general X.Equals(Y) will only be true if replacing arbitrary references to X with references to Y, and/or vice versa, would not be expected to alter the semantics of the objects in question. For example, if X is a String with the content “Hello”, and Y is a different string with that same content, replacing references to one string with references to the other would not generally alter their behavior. Although code which uses ReferenceEquals to test whether two string references refer to the same string might notice the switch, normal string code would not.

As a general rule, no mutable object is equivalent to any other, and thus no reference to a mutable object should be equivalent to another unless both references refer to the same object. There is a big difference between having references to two different instances of int[], both of which hold the same values, versus having two references to the same instance. While it would be helpful for Array to have ItemsEqual methods which would test whether all items of the arrays, or certain ranges of items, matched, and it would be helpful to have an ImmutableArray type with a Equals/GetHashCode members that would regard as equal two immutable arrays with the same content, it is entirely right and proper that distinct mutable arrays compare unequal to each other regardless of content.

Leave a Comment