Equals on incomparable types¶
ID: cs/equals-on-unrelated-types Kind: problem Security severity: Severity: error Precision: high Tags: - quality - reliability - correctness Query suites: - csharp-code-quality.qls - csharp-security-and-quality.qls Click to see the query in the CodeQL repository
Calling x.Equals(y) on incomparable types will almost always return false. If two classes do not have a common parent class their instances are considered incomparable.
Recommendation¶
Carefully check the code for errors.
Example¶
In this example both calls to the Equals method will always return false regardless of the contents of the ArrayList or String because ArrayLists and Strings are incomparable.
using System.Collections; class IncomparableEquals { public static void Main(string[] args) { ArrayList apple = new ArrayList(); String orange = "foo"; Console.WriteLine(apple.Equals(orange)); // BAD Console.WriteLine(orange.Equals(apple)); // BAD } } References¶
MSDN, Object.Equals Method.