A class that compares values calls object's identity-based hash code or equality from its overrides
What it finds
For a class that derives from object directly, base.GetHashCode() is the hash of the object's identity and base.Equals(other) is reference equality. In a class that overrides both to compare values, calling the base in one of them undoes the other: equal values get different hash codes, so dictionaries and sets miss them, or Equals is false for every pair of distinct objects, as in return base.Equals(obj) && Id == other.Id;.
Reported are, in a class without a base class that overrides both, base.GetHashCode() when Equals does not call base.Equals, and base.Equals joined with && to other comparisons. An Equals that is reference equality agrees with any hash code. Tests are left alone. Base lists whose entries all look like interfaces (I and a capital letter) count as no base class.
From the rule's source, object_identity_in_value_equality.rs.
public class Account{ public int Id; public override bool Equals(object obj) => obj is Account other && Id == other.Id; public override int GetHashCode() => base.GetHashCode();tx0 reports: base.GetHashCode() is the hash of the object's identity, but Equals compares values} public class Order{ public int Id; public override bool Equals(object obj) => base.Equals(obj) && obj is Order other && Id == other.Id;tx0 reports: base.Equals is reference equality here, so distinct objects are never equal public override int GetHashCode() => Id;} public class Entity{ public int Id; public override bool Equals(object obj) => obj is Entity other && Id == other.Id; public override int GetHashCode() => Id;} public class Customer : Entity{ public string Name; public override bool Equals(object obj) => base.Equals(obj) && obj is Customer c && Name == c.Name; public override int GetHashCode() => base.GetHashCode();} public class Handle{ public override string ToString() => base.ToString(); public override int GetHashCode() => base.GetHashCode();} Turn it on, off or suppress it
The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/csharp:object-identity-in-value-equality" = "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:object-identity-in-value-equality] reason="..."tx0 explain tx0/csharp:object-identity-in-value-equality shows the same in the terminal. Found a false positive? Report it.