Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.