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.

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

  • MSDN: ContainsKey Method, TryGetValue Method.