CodeQL documentation

Useless call to GetHashCode()

ID: cs/useless-gethashcode-call
Kind: problem
Security severity: 
Severity: recommendation
Precision: high
Tags:
   - readability
   - useless-code
Query suites:
   - csharp-security-and-quality.qls

Click to see the query in the CodeQL repository

The method GetHashCode() on an integer simply returns the original value of the integer. This method call is therefore redundant, inefficient, and obscures the logic of the hash function. Several of the built-in types have this behavior, including int, uint, short, ushort, long, ulong, byte and sbyte.

Recommendation

Remove the call to GetHashCode(), and review the hash function.

Example

The following hash function has two problems. Firstly, the calls to GetHashCode() are redundant, and secondly, the hash function generates too many collisions.

public override int GetHashCode()
{
    return row.GetHashCode() ^ col.GetHashCode();
}

These problems are resolved by removing the redundant calls to GetHashCode(), and by changing the hash function to generate fewer collisions.

public override int GetHashCode()
{
    return unchecked(row * 16777619 + col);
}

References

  • © GitHub, Inc.
  • Terms
  • Privacy