Skip to content

Instantly share code, notes, and snippets.

@hidori
Created February 6, 2015 08:39
Show Gist options
  • Save hidori/0c2bf7ec1929b867d3f8 to your computer and use it in GitHub Desktop.
Save hidori/0c2bf7ec1929b867d3f8 to your computer and use it in GitHub Desktop.
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