
TryGetValue optimizes Dictionary usage. It allows you to store the value found in the Dictionary after a lookup. This eliminates unnecessary lookups that might occur after ContainsKey returns true. TryGetValue is one of the most important C# Dictionary methods.
First, we look at how you can rewrite programs that use ContainsKey with TryGetValue. Even developers who understand Dictionary and how hashtable lookups work can make this mistake. It also gives us an interesting insight into how hashtables in C# work. We apply the TryGetValue method in the C# language.
These C# example programs show the TryGetValue method on the Dictionary type. TryGetValue improves performance.
Program that uses ContainsKey [C#]
using System.Collections.Generic;
class Program
{
static void Main()
{
var d = new Dictionary<string, int>();
d.Add("key", 0);
// Does three lookups in Dictionary.
if (d.ContainsKey("key"))
{
d["key"]++;
}
}
}
Program that shows what ContainsKey does [C#]
using System.Collections.Generic;
class Program
{
static void Main()
{
var d = new Dictionary<string, int>();
d.Add("key", 0);
// This code is equivalent to the previous example.
if (d.ContainsKey("key"))
{
d["key"] = d["key"] + 1;
}
}
}
Program that uses TryGetValue [C#]
using System.Collections.Generic;
class Program
{
static void Main()
{
var d = new Dictionary<string, int>();
d.Add("key", 0);
// This code does two hash lookups.
int value;
if (d.TryGetValue("key", out value))
{
d["key"] = value + 1;
}
}
}
First example. The problematic code increments or decrements the value of a Dictionary at a key. Skilled developers usually increment using the ++ operator. However, on a Dictionary this is a bad choice.
Second example. The increment does two lookups when you really only need one in the common case above. To increment the value of the Dictionary, you have to get the current value.
Third example with TryGetValue. Every lookup in a hash on a string key has to compute the hash code, which has a performance penalty. To solve this inefficiency, use the TryGetValue method. You can store the value it finds.

Here we look at how the TryGetValue method performs when used in the way in the above example. I am so used to using the ++ operator (or —) on integers, that this slipped through my review. Expert developers understand precisely what their code is doing. So knowing this is much more important than simply making the code twice as fast.
Benchmark results for TryGetValue Use ContainsKey: 1700 ms Use TryGetValue: 1108 ms [faster]

You can rewrite your Dictionary code to use TryGetValue instead of ContainsKey. It is advantageous to avoid the ++ or — operators on Dictionary. Instead, store the value with TryGetValue. Careful and precise understanding of how hashtable lookups work in .NET and C# helps improve your code significantly.
Collections