C# Dictionary.GetValueOrDefault()

This is one of those methods that you can’t believe was missed. If you have a C# Dictionary <string, OtherClass> myDict; and you then access dict["dave"] where “dave” is not in the Doctionary, it throws an exception.

The natural call to have is one where it returns a null if that entry does not exist. So I added an extension class. Here it is:

/// <summary>
/// Get a the value for a key. If the key does not exist, return null;
/// </summary>
/// <typeparam name="TKey">The type of the keys in the dictionary.</typeparam>
/// <typeparam name="TValue">The type of the values in the dictionary.</typeparam>
/// <param name="dic">The dictionary to call this method on.</param>
/// <param name="key">The key to look up.</param>
/// <returns>The key value. null if this key is not in the dictionary.</returns>
public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> dic, TKey key)
{
    TValue result;
    return dic.TryGetValue(key, out result) ? result : default(TValue);
}