Advertisement
Advanced C#, Equality: Equals, GetHashCode & IEquatable

How does structural (deep) equality for collections work, and why doesn't List<T>.Equals() perform element-by-element comparison by default?

Short answer

List (and most standard collections) inherit REFERENCE equality from Object by default — two lists with identical elements are NOT considered equal via Equals() unless you use a dedicated comparison method like Enumerable.SequenceEqual(), which explicitly walks both sequences…

Save C# mock interview
Advertisement
AModel answer
List<T> (and most standard collections) inherit REFERENCE equality from Object by default — two lists with identical elements are NOT considered equal via Equals() unless you use a dedicated comparison method like Enumerable.SequenceEqual(), which explicitly walks both sequences and compares corresponding elements pairwise.
var list1 = new List<int> { 1, 2, 3 };
var list2 = new List<int> { 1, 2, 3 };
Console.WriteLine(list1.Equals(list2));           // False -- reference equality
Console.WriteLine(list1.SequenceEqual(list2));    // True -- explicit element-by-element comparison
Real-world example
Correctly comparing two lists of parsed data for content equality in a unit test assertion, rather than accidentally comparing references.
Likely follow-ups
  • Does SequenceEqual() also check that both sequences are the SAME LENGTH before comparing elements?
Related topics