Runtime: Create standard Dictionary class that doesn't throw a KeyNotFoundException

Created on 11 Sep 2019  路  2Comments  路  Source: dotnet/runtime

Feature Request

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
}

Solution

A standard Dictionary-like class that does not throw KeyNotFoundExeption when key is missing, just returns null when using the [] operator.

Additional context

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:

https://stackoverflow.com/questions/14150508/how-to-get-null-instead-of-the-keynotfoundexception-accessing-dictionary-value-b

leading to managing a utility project and duplicate code in the .net ecosystem

api-suggestion area-System.Collections

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.

All 2 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

iCodeWebApps picture iCodeWebApps  路  3Comments

yahorsi picture yahorsi  路  3Comments

EgorBo picture EgorBo  路  3Comments

matty-hall picture matty-hall  路  3Comments

GitAntoinee picture GitAntoinee  路  3Comments