Skip to content

Proposal: Dictionary<TKey, TValue>.TryAdd(TKey, TValue) #14676

@stephentoub

Description

@stephentoub

It's very common to see code that does this:

Dictionary<TKey, TValue> data = ...;
...
if (!data.ContainsKey(key))
    data.Add(key, value);

This forces the dictionary to lookup the key twice when the key isn't yet in the dictionary.

It'd be great if we had an additional method on the type:

public bool TryAdd(TKey key, TValue value);

Functionally it would behave exactly as if it were implemented like:

public bool TryAdd(TKey key, TValue value)
{
    if (ContainsKey(key)) return false;
    Add(key, value);
    return true;
}

but the implementation internally would be done more efficiently, essentially implemented by calling a variant of Insert but that returns false instead of throwing when a duplicate key is found.

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedAPI was approved in API review, it can be implementedarea-System.Collectionshelp wanted[up-for-grabs] Good issue for external contributors

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions