Skip to content

[API Proposal]: Dictionary<TKey, TValue>.KeysCollection.Contains #75936

@stephentoub

Description

@stephentoub

Background and motivation

Dictionary<TKey, TValue>.Keys returns a Dictionary<TKey, TValue>.KeysCollection. This type implements ICollection<TKey> and has an efficient implementation of ICollection<TKey>.Contains... but it's explicitly implemented. That means if you do:

Dictionary<TKey, TValue> d = ...;
...
if (d.Keys.Contains(...)) { ... }

you end up invoking Enumerable.Contains. This does a dynamic check for ICollection and delegates to it, but that's still unnecessary overhead. We can easily fix this by making KeysCollection.Contains public / implicitly implemented.

API Proposal

namespace System.Collections.Generic;

public class Dictionary<TKey, TValue>
{
    public sealed class KeyCollection
    {
-        bool ICollection<TKey>.Contains(TKey item)
+        public bool Contains(TKey item);
    }
}

public class SortedDictionary<TKey, TValue>
{
    public sealed class KeyCollection
    {
-        bool ICollection<TKey>.Contains(TKey item)
+        public bool Contains(TKey item);
    }
}

API Usage

if (dictionary.Keys.Contains(...))

Alternative Designs

No response

Risks

No response

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions