Skip to content

Instantly share code, notes, and snippets.

@GeorgeTsiokos
Created January 26, 2018 20:37
Show Gist options
  • Save GeorgeTsiokos/8c3300534088ab8e2dff9a279c9a618f to your computer and use it in GitHub Desktop.
Save GeorgeTsiokos/8c3300534088ab8e2dff9a279c9a618f to your computer and use it in GitHub Desktop.
[PublicAPI]
public static partial class DictionaryExtensions
{
/// <summary>
/// Adds a key/value pair to the <see cref="T:System.Collections.Generic.IDictionary`2" /> by using the specified
/// function, if the key does not already exist.
/// </summary>
/// <param name="dictionary">the dictionary to get or add from</param>
/// <param name="key">The key of the element to add.</param>
/// <param name="valueFactory">The function used to generate a value for the key</param>
/// <returns>
/// The value for the key. This will be either the existing value for the key if the key is already in the
/// dictionary, or the new value for the key as returned by valueFactory if the key was not in the dictionary.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="key" /> or <paramref name="valueFactory" /> is <see langword="null" />.
/// </exception>
/// <exception cref="T:System.OverflowException">
/// The dictionary already contains the maximum number of elements (
/// <see cref="F:System.Int32.MaxValue" />).
/// </exception>
[ContractAnnotation("dictionary:null => halt; key:null => halt; valueFactory:null => halt")]
public static TValue GetOrAdd<TKey, TValue>([NotNull] this IDictionary<TKey, TValue> dictionary, [NotNull] TKey key, [NotNull] Func<TKey, TValue> valueFactory)
{
if (dictionary == null)
throw new ArgumentNullException(nameof(dictionary));
if (key == null)
throw new ArgumentNullException(nameof(key));
if (valueFactory == null)
throw new ArgumentNullException(nameof(valueFactory));
if (dictionary.TryGetValue(key, out var result))
return result;
result = valueFactory(key);
dictionary.Add(key, result);
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment