IDictionary <TKey, TValue> implementation and replacement contract

Is there a “contract” for the interface IDictionary<TKey, TValue>I should follow when implementing a value substitution using this[key] = newValue? Example:

IDictionary<MyKey, string> dict = CreateEmptyDict();
var k1 = new MyKey(123);
var k2 = new MyKey(123);  
dict.Add(k1, "foo");
dict[k2] = "bar";

k1 and k2 are such that k1.Equals(k2)they have the same hash code, but they are reference types, therefore ReferenceEquals(k1, k2) == false.

BCL Dictionary<TKey, TValue>will contain (k1, "bar"). My question is: is this a “contract” that I really must adhere to for any implementation IDictionary<TKey, TValue>, or can I let my implementation contain (k2, "bar")if it's easier to do in the underlying data structure?

+4
source share
1 answer

, , . , Dictionary<,> IEqualityComparer<T>, , SortedDictionary<,> Equals GetHashCode - IComparer<T> .

, , , . , IDictionary<,> , ... Dictionary<,> , RuntimeHelpers.GetHashCode(), -, Object.GetHashCode() , .

, , , , , , IMO.

+5

Source: https://habr.com/ru/post/1624230/


All Articles