TheDeveloperBlog.com


C# TryGetValue Method

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.


Example. 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.

ContainsKey

Also: It gives us insight into how hashtables in C# work. We apply the TryGetValue method in the C# language.

Based on:

.NET 4

C# program that uses ContainsKey

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"]++;
	}
    }
}

C# program that shows what ContainsKey does

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;
	}
    }
}

C# program that uses TryGetValue

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;
	}
    }
}

In the first example, the problematic code increments the value of a Dictionary. Skilled developers usually increment using the ++ operator. But on a Dictionary the ++ operator is a bad choice. It leads to more hash table lookups.

Second example: Here the increment does two lookups when we only need one. To increment the value in the Dictionary, we have to get it.

Third example, 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.


Benchmark. We see 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.

Tip: Expert developers understand precisely what their code is doing. This is more important than making the code twice as fast.

Benchmark results for TryGetValue

Use ContainsKey: 1700 ms
Use TryGetValue: 1108 ms [faster]


Summary. 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.