I really hate sometimes when it IDictionary<TKey, TValue> [key]
throws an exception if the key does not exist in the dictionary.
Of course there is TryGetValue()
, but it seems to be optimized for performance, and not for ease of use.
So, I thought, oh, I'll just do an extension method for it - what I did:
public static class CollectionExtensions
{
public static TType GetValueOrDefault<TKeyType, TValue, TType>(this IDictionary<TKeyType, TType> dictionary, TKeyType key)
{
TType value = default(TType);
if (dictionary.TryGetValue(key, out value))
{
return value;
}
else
{
return default(TType);
}
}
}
This works fine EXCEPTION I cannot get it to work with the output type.
Obviously, I want to be able to do the following:
var extraDataLookup = new Dictionary<string, string>();
extraDataLookup["zipcode"] = model.Zipcode;
and then access the value:
var zipcode = extraDataLookup.GetValueOrDefault("zipcode");
var foo = extraDataLookup.GetValueOrDefault("foo");
I looked at a few things about type inferences by introducing a Jon Skeet article and even the source code into System.Linq.Enumerable
a reflector , but there seems to be something missing.
It works:
extraDataLookup.GetValueOrDefault<string, string,string> ("foo")
But it is not
extraDataLookup.GetValueOrDefault ("foo")
What should I do.
PS. , . .