Hashed value without GetHashCode definition¶
ID: cs/gethashcode-is-not-definedKind: problemSecurity severity: Severity: warningPrecision: highTags: - quality - reliability - correctnessQuery suites: - csharp-security-and-quality.qls
Click to see the query in the CodeQL repository
Classes that overrideSystem.Object.Equals() but notSystem.Object.GetHashCode() can yield unexpected results if instances of those classes are stored in a hashing data structure.
Recommendation¶
Override theGetHashCode method such that for two instances a and b, where a.Equals(b) is true, a.GetHashCode() and b.GetHashCode() are equal. The C# documentation states [1]:
If two objects compare as equal, the GetHashCode method for each object must return the same value. However, if two objects do not compare as equal, the GetHashCode methods for the two objects do not have to return different values.
Example¶
usingSystem;usingSystem.Collections;classPoint{privateintx;privateinty;publicPoint(intx,inty){this.x=x;this.y=y;}publicoverrideboolEquals(Objectother){Pointpoint=otherasPoint;if(point==null){returnfalse;}returnthis.x==point.x&&this.y==point.y;}publicstaticvoidMain(string[]args){Hashtablehashtable=newHashtable();hashtable[newPoint(5,4)]="A point";// BAD// Point overrides the Equals method but not GetHashCode.// As such it is probably not useful to use one as the key for a Hashtable.Console.WriteLine(hashtable[newPoint(5,4)]);}}
References¶
MSDN, C# Programmer’s Reference,Object.GetHashCode