From aefc33042d77bdf11431a9ab9fcfd77f5d85e34d Mon Sep 17 00:00:00 2001 From: aw0lid Date: Thu, 19 Nov 2026 00:22:04 +0200 Subject: [PATCH] Fix HashSet.UnionWith IndexOutOfRangeException when emptied by removals --- .../Generic/HashSet/HashSet.Generic.Tests.cs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/libraries/System.Collections/tests/Generic/HashSet/HashSet.Generic.Tests.cs b/src/libraries/System.Collections/tests/Generic/HashSet/HashSet.Generic.Tests.cs index ef70bbda6490ea..be5b4166150584 100644 --- a/src/libraries/System.Collections/tests/Generic/HashSet/HashSet.Generic.Tests.cs +++ b/src/libraries/System.Collections/tests/Generic/HashSet/HashSet.Generic.Tests.cs @@ -1001,6 +1001,25 @@ public void HashSet_Generic_UnionWith_HashSet(int count, bool destinationEmpty, Assert.True(expected.SetEquals(destination)); } + [Fact] + public void HashSet_UnionWith_ThrowsWhenDestinationEmptiedByRemove() + { + var target = new HashSet(StringComparer.Ordinal) { "s0" }; + target.Remove("s0"); + + var source = new HashSet(StringComparer.Ordinal); + for (int i = 0; i < 8; i++) + source.Add("k" + i); + + for (int i = 0; i < 4; i++) + source.Remove("k" + i); + + target.UnionWith(source); + + Assert.Equal(4, target.Count); + Assert.True(target.SetEquals(new[] { "k4", "k5", "k6", "k7" })); + } + #endregion } }