Skip to content

Commit a582842

Browse files
authored
Fix missing hashcode set in OrderedDictionary.SetAt (#103643)
1 parent 7172a7d commit a582842

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

src/libraries/System.Collections/src/System/Collections/Generic/OrderedDictionary.cs

+3-2
Original file line numberDiff line numberDiff line change
@@ -809,8 +809,8 @@ public void SetAt(int index, TKey key, TValue value)
809809
}
810810

811811
// The key doesn't match that index. If it exists elsewhere in the collection, fail.
812-
uint _ = 0, collisionCount = 0;
813-
if (IndexOf(key, ref _, ref collisionCount) >= 0)
812+
uint hashCode = 0, collisionCount = 0;
813+
if (IndexOf(key, ref hashCode, ref collisionCount) >= 0)
814814
{
815815
ThrowHelper.ThrowDuplicateKey(key);
816816
}
@@ -820,6 +820,7 @@ public void SetAt(int index, TKey key, TValue value)
820820
// (we could check for this, but in a properly balanced dictionary the chances should
821821
// be low for a match, so it's not worth it).
822822
RemoveEntryFromBucket(index);
823+
e.HashCode = hashCode;
823824
e.Key = key;
824825
e.Value = value;
825826
PushEntryIntoBucket(ref e, index);

src/libraries/System.Collections/tests/Generic/OrderedDictionary/OrderedDictionary.Generic.Tests.cs

+19
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,25 @@ public void OrderedDictionary_Generic_SetAt_GetAt_Roundtrip(int count)
308308
}
309309
}
310310

311+
[Fact]
312+
public void OrderedDictionary_SetAt_KeyValuePairSubsequentlyAvailable()
313+
{
314+
TKey key0 = CreateTKey(0), key1 = CreateTKey(1);
315+
TValue value0 = CreateTValue(0), value1 = CreateTValue(1);
316+
317+
var dict = new OrderedDictionary<TKey, TValue>
318+
{
319+
[key0] = value0,
320+
};
321+
322+
dict.SetAt(index: 0, key1, value1);
323+
324+
Assert.Equal(1, dict.Count);
325+
Assert.Equal([new(key1, value1)], dict);
326+
Assert.False(dict.ContainsKey(key0));
327+
Assert.True(dict.ContainsKey(key1));
328+
}
329+
311330
#endregion
312331

313332
#region Remove(..., out TValue)

0 commit comments

Comments
 (0)