Equals(object) casts its argument without checking its type, so comparing with another type throws
What it finds
Equals(object) may be called with any object, including null and objects of other types: collections of object and object.Equals(a, b) do so. An override that casts the argument with (T)other throws InvalidCastException or NullReferenceException instead of returning false. The rule reports such a cast when the method never tests the argument with is, as, GetType or a comparison with null.
From the rule's source, equals_casts_unchecked.rs.
class Key{ public int Id; public override bool Equals(object obj) { var other = (Key)obj;tx0 reports: the argument of Equals is cast without checking its type return other.Id == Id; } public override int GetHashCode() => Id;} class SafeKey{ public int Id; public override bool Equals(object obj) { if (obj == null || obj.GetType() != GetType()) { return false; } return ((SafeKey)obj).Id == Id; } public override int GetHashCode() => Id;} 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:equals-casts-unchecked" = "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:equals-casts-unchecked] reason="..."tx0 explain tx0/csharp:equals-casts-unchecked shows the same in the terminal. Found a false positive? Report it.