Created
February 6, 2015 08:39
-
-
Save hidori/0c2bf7ec1929b867d3f8 to your computer and use it in GitHub Desktop.
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
static class DictionaryExtensions | |
{ | |
public static T GetValueOrDefault<T>(this IDictionary<string, object> source, string name) | |
{ | |
if (source == null) throw new ArgumentNullException("source"); | |
if (name == null) throw new ArgumentNullException("name"); | |
var value = default(object); | |
return (source.TryGetValue(name, out value) && (value is T)) | |
? (T)value | |
: default(T); | |
} | |
} | |
/* | |
void Main() | |
{ | |
var dictionary = new Dictionary<string, object> | |
{ | |
{ "a", 1 }, | |
{ "b", "b" }, | |
}; | |
var a = dictionary.GetValueOrDefault<int>("a"); | |
Console.WriteLine(a); | |
var b = dictionary.GetValueOrDefault<string>("b"); | |
Console.WriteLine(b); | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment