Created
February 11, 2013 09:32
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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