Skip to content

Instantly share code, notes, and snippets.

@GrahamTheCoder
Created September 26, 2019 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GrahamTheCoder/e7d510b665e967a59323f12ef5e1145b to your computer and use it in GitHub Desktop.
Save GrahamTheCoder/e7d510b665e967a59323f12ef5e1145b to your computer and use it in GitHub Desktop.
DictionaryExtensions
public static class DictionaryExtensions
{
public static TValue Get<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dict, TKey key, TValue defaultValue = default(TValue))
=> dict.TryGetValue(key, out var actualValue) ? actualValue : defaultValue;
public static TValue Get<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue defaultValue = default(TValue))
=> dict.TryGetValue(key, out var actualValue) ? actualValue : defaultValue;
public static TValue Get<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue defaultValue = default(TValue))
=> dict.TryGetValue(key, out var actualValue) ? actualValue : defaultValue;
public static TValue? GetNullable<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dict, TKey key)
where TValue: struct => dict.TryGetValue(key, out var actualValue) ? actualValue : default(TValue?);
public static TValue? GetNullable<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key)
where TValue : struct => dict.TryGetValue(key, out var actualValue) ? actualValue : default(TValue?);
public static TValue? GetNullable<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key)
where TValue : struct => dict.TryGetValue(key, out var actualValue) ? actualValue : default(TValue?);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment