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;
}
}
The KeyValuePair class should implement IEquatable<T>.
Consider the sample below. It doesn't compile due to the constraint.
In our performance critical application, reading the
Valuesproperty is not an option. Now we faced the above problem, where ourIEquatable<T>aware APIs cannot be used in this context.Current declaration:
Should be:
Current workaround involves allocating an intermediate enumerator: