CodeQL documentation

Inefficient use of ContainsKey

ID: cs/inefficient-containskey
Kind: problem
Severity: recommendation
Precision: high
   - maintainability
   - efficiency
Query suites:
   - csharp-security-and-quality.qls

Click to see the query in the CodeQL repository

Using the ContainsKey method to check whether a dictionary contains a value before getting the value is inefficient because it performs two operations on the dictionary. It is simpler and more efficient to combine the operations using the TryGetValue method.


Replace the two operations with a single call to TryGetValue.


This code first checks whether ip is in the hostnames table, before looking up the value.

// BAD: Two operations on the hostnames table.

  return hostnames[ip];

This code performs the same function as the example above, but uses TryGetValue, which makes it is more efficient.

// GOOD: One operation on the hostnames table.

if(hostnames.TryGetValue(ip, out hostname))
  return hostname;