Add equality override for KeyValuePairComparer (#56634)
authorJohn Call <johncall@microsoft.com>
Mon, 2 Aug 2021 16:29:53 +0000 (09:29 -0700)
committerGitHub <noreply@github.com>
Mon, 2 Aug 2021 16:29:53 +0000 (17:29 +0100)
src/libraries/System.Collections/src/System/Collections/Generic/SortedDictionary.cs

index 35da349..c28fa01 100644 (file)
@@ -947,6 +947,21 @@ namespace System.Collections.Generic
             {
                 return keyComparer.Compare(x.Key, y.Key);
             }
+
+            public override bool Equals(object? obj)
+            {
+                if (obj is KeyValuePairComparer other)
+                {
+                    // Commonly, both comparers will be the default comparer (and reference-equal). Avoid a virtual method call to Equals() in that case.
+                    return this.keyComparer == other.keyComparer || this.keyComparer.Equals(other.keyComparer);
+                }
+                return false;
+            }
+
+            public override int GetHashCode()
+            {
+                return this.keyComparer.GetHashCode();
+            }
         }
     }