Skip to content

KeyValuePair<TKey, TValue> should implement IEquatable<T> #35602

@znakeeye

Description

@znakeeye

The KeyValuePair class should implement IEquatable<T>.

Consider the sample below. It doesn't compile due to the constraint.

class Program
{
    class Foo : IEquatable<Foo>
    {
        public bool Equals(Foo other) => false;
    }

    static void Bar<T>(IEnumerable<T> items) where T : IEquatable<T>
    {
        // Code that relies on IEquatable<T>
    }

    static void Main(string[] args)
    {
        var dic = new Dictionary<string, Foo>();
        
        Bar(dic);        // CS0315
        Bar(dic.Values); // ok, but produces more garbage
    }
}

In our performance critical application, reading the Values property is not an option. Now we faced the above problem, where our IEquatable<T> aware APIs cannot be used in this context.

Current declaration:

public readonly struct KeyValuePair<TKey, TValue>

Should be:

public readonly struct KeyValuePair<TKey, TValue> : IEquatable<KeyValuePair<TKey, TValue>>

Current workaround involves allocating an intermediate enumerator:

private static IEnumerable<TValue> GetItems<TKey, TValue>(Dictionary<TKey, TValue> dic)
    where TValue : IEquatable<TValue>
{
    foreach (var kvp in dic)
    {
        yield return kvp.Value;
    }
}

Metadata

Metadata

Type

No type
No fields configured for issues without a type.

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions