Skip to content

Instantly share code, notes, and snippets.

@Reizinixc
Created November 27, 2016 16:20
Show Gist options
  • Save Reizinixc/76b7e1b6a0456f0fe54de5efcafec65d to your computer and use it in GitHub Desktop.
Save Reizinixc/76b7e1b6a0456f0fe54de5efcafec65d to your computer and use it in GitHub Desktop.
TryGetValueOrDefault for dictionary interface
/// <summary>
/// Gets the value that associated with the specified key in provided dictionary,
/// or returns the default value of the value's type when the key is not associate.
/// </summary>
/// <typeparam name="K">Type of dictionary key.</typeparam>
/// <typeparam name="V">Type of dictionary value.</typeparam>
/// <param name="dict">A dictionary instance to be got the value.</param>
/// <param name="key">A key to be searched in the dictionary.</param>
/// <returns>
/// The value associated with the specified key. If the key is not exist in
/// provided dictionary, returns the default value of dictionary's value type.
/// </returns>
public static V TryGetValueOrDefault<K, V>(this IDictionary<K, V> dict, K key)
{
V value;
return dict.TryGetValue(key, out value) ? value : default(V);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment