.NET Framework Getting a value from a dictionary


Given this setup code:

var dict = new Dictionary<int, string>()
    { 1, "First" },
    { 2, "Second" },
    { 3, "Third" }

You may want to read the value for the entry with key 1. If key doesn't exist getting a value will throw KeyNotFoundException, so you may want to first check for that with ContainsKey:

if (dict.ContainsKey(1))

This has one disadvantage: you will search through your dictionary twice (once to check for existence and one to read the value). For a large dictionary this can impact performance. Fortunately both operations can be performed together:

string value;
if (dict.TryGetValue(1, out value))