A hash code is computed from a field that can change while the object is in a hash table
What it finds
A dictionary or a hash set files an object under the hash code it has when it is added. If GetHashCode reads a field that changes afterwards, the object sits under its old hash: lookups miss it, Remove fails and the set can hold it twice. Hash codes should come from fields that do not change once the object is built, readonly fields and properties without a setter or with init only.
Reported is the first read, in a GetHashCode override of a class that also overrides Equals, of an instance field that is not readonly or of an auto-property of the class with a set accessor.
From the rule's source, hash_code_of_mutable_field.rs.
public class Point{ public int X; private readonly int y; public Point(int y) { this.y = y; } public override bool Equals(object obj) => obj is Point p && p.X == X && p.y == y; public override int GetHashCode() => y * 31 + X;tx0 reports: GetHashCode reads X, which can change after the object is hashed} public class Key{ public string Name { get; set; } public int Id { get; init; } public override bool Equals(object obj) => obj is Key k && k.Name == Name; public override int GetHashCode() => this.Name.GetHashCode();tx0 reports: GetHashCode reads Name, which can change after the object is hashed} public class Fixed{ public int Id { get; } private readonly string code = "a"; private int hits; public override bool Equals(object obj) => obj is Fixed f && f.Id == Id; public override int GetHashCode() => Id ^ code.GetHashCode();} public class Counter{ public int Count; public override int GetHashCode() => Count;} Turn it on, off or suppress it
The rule runs from the strict tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/csharp:hash-code-of-mutable-field" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/csharp:hash-code-of-mutable-field] reason="..."tx0 explain tx0/csharp:hash-code-of-mutable-field shows the same in the terminal. Found a false positive? Report it.