While Dictionary allows you to get a value or default(T) via GetValueOrDefault, the corresponding IDictionary doesn't allow you to do the same and instead provides two cumbersome methods like:
operator[] (which throws if the key doesn't exist)TryGetValue (which uses out parameters)Coming from a C++ background I'm taught to think that if something that trivial is not provided it's probably because of a performance issue, but at the same time it's trivial to define an extension method using one of the two methods above:
public static class IDictionaryExtensions
{
public static T GetValueOrDefault<K, T>(this IDictionary<K, T> dictionary, K key)
{
var value = default(T);
bool hasValue = dictionary.TryGetValue(key, out value);
if (hasValue) {
return value;
} else {
return default(T);
}
}
}
Is there any reason why this method is not provided? If not, is the above implementation equivalent to Dictionary.GetValueOrDefault?
Only the people in .NET team can answer as to "why" a function is not provided.
As for your method, it looks fine but there are few redundant statements you can remove. It can be rewritten like this:
return dictionary.TryGetValue(key, out var value) ? value : default(T);
IMO this is redundant too because if TryGetValue returns false, the value will be initialized to default anyways. So whenever you need to use GetValueOrDefault, you can just use TryGetValue, inline out variable declarations makes it easy to use in a single line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With