Skip to content

Instantly share code, notes, and snippets.

@Nilzor
Created February 11, 2013 09:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Nilzor/4753489 to your computer and use it in GitHub Desktop.
Save Nilzor/4753489 to your computer and use it in GitHub Desktop.
DictionaryExtensions - safer and simpler get avoiding exceptions. See http://www.nilzorblog.com/2013/01/improving-generic-c-dictionary-with.html
public static class DictionaryExtensions
{
/// <summary>
/// Returns a default value of type U if the key does not exist in the dictionary
/// </summary>
/// <param name="dic">The dictionary to search</param>
/// <param name="key">Key to search for</param>
/// <param name="onMissing">Optional default value of type U. If not specified, the C# default value will be returned.</param>
public static U GetOrDefault<T, U>(this Dictionary<T, U> dic, T key, U onMissing = default(U))
{
U value;
return dic.TryGetValue(key, out value) ? value : onMissing;
}
/// <summary>
/// Returns an existing value U for key T, or creates a new instance of type U using the default constructor,
/// adds it to the dictionary and returns it.
/// </summary>
public static U GetOrInsertNew<T, U>(this Dictionary<T, U> dic, T key)
where U : new()
{
if (dic.ContainsKey(key)) return dic[key];
U newObj = new U();
dic[key] = newObj;
return newObj;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment