Skip to content

Commit

Permalink
Clarifying GetHashCode for collections
Browse files Browse the repository at this point in the history
  • Loading branch information
lookbusy1344 committed Oct 24, 2023
1 parent 3712968 commit 16085a9
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,22 @@ public record struct Test(IReadOnlyList<int> Numbers)
}
```

It is not necessary for records to implement `IEquatable<T>`. When you write your implementations `SequenceEqual` is very useful for comparing collections, eg:
It is not necessary for records to implement `IEquatable<T>`. When you write your implementations `SequenceEqual` is very useful for comparing collections.

Note that GetHashCode for collections is tricky!

```
public readonly bool Equals(Test other) => Numbers.SequenceEqual(other.Numbers);
public override readonly int GetHashCode() => Numbers.GetHashCode();
public override int GetHashCode() => Numbers.GetHashCode(); // BROKEN!
public override int GetHashCode() => HashCode.Combine(Numbers); // BROKEN!
public override int GetHashCode() // CORRECT IMPLEMENTATION
{
var hash = new HashCode();
foreach (var n in Numbers) hash.Add(n);
return hash.ToHashCode();
}
public readonly bool Equals(Test other) => Numbers.SequenceEqual(other.Numbers); // CORRECT IMPLEMENTATION
```

## Testing
Expand Down

0 comments on commit 16085a9

Please sign in to comment.