Dictionaries make a missing element an "KeyNotFoundException" event when in reality is quite common place and can be better managed by a null check when an item in the dictionary.
This leads to clunky code like
if (dict.TryGetValue(key, out var value))
{
//do work here
}
A standard Dictionary-like class that does not throw KeyNotFoundExeption when key is missing, just returns null when using the [] operator.
This increases the level of complexity for newcomers to the language or coming from another language where the expected behavior when a dictionary is missing a key to return null.
Additionally, in MANY cases it completely eliminates the [ ] operator being used at all.
Often developers have to create a custom implementation for accessing dictionaries such can be found here:
leading to managing a utility project and duplicate code in the .net ecosystem
I don't think we will accept a second Dictionary class with only this behavior change, as duplicating the API surface like that would not provide enough value. Try* is a common pattern in .NET and there has been no pull to move away from that. This also has problems with values that are not nullable, so structs could only return their default value which may not be what people expect especially for non-integer structs.
I'm going to close the issue, but would encourage some conversation to help us understand why TryGetValue is clunky for your workload. CC @safern
I agree with @scalablecory this is the standard pattern in .NET plus the extension method alternative is simple, from the SO post:
c#
public static TV GetValue<K, V>(this IDictionary<K, V> dict, K key, V defaultValue = default(V))
{
V value;
return dict.TryGetValue(key, out value) ? value : defaultValue;
}
That doesn't need maintenance.
Most helpful comment
I agree with @scalablecory this is the standard pattern in .NET plus the extension method alternative is simple, from the SO post:
c# public static TV GetValue<K, V>(this IDictionary<K, V> dict, K key, V defaultValue = default(V)) { V value; return dict.TryGetValue(key, out value) ? value : defaultValue; }That doesn't need maintenance.