Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't `IDictionary` allow you to easily get a value by key or default in its interface?

Tags:

c#

.net

.net-core

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?

like image 882
Shoe Avatar asked Dec 17 '25 14:12

Shoe


1 Answers

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.

like image 121
Selman Genç Avatar answered Dec 20 '25 06:12

Selman Genç



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!