dotnet / dotnet-api-docs

.NET API reference documentation (.NET 5+, .NET Core, .NET Framework)
https://docs.microsoft.com/dotnet/api/
Other
739 stars 1.57k forks source link

Hashset Remove is not throwing on enumeration #8177

Open wrexbe opened 2 years ago

wrexbe commented 2 years ago

Description

I found some code that was looping over a hashset, and removing items. Hashset is not throwing when you remove while enumerating like it used to. It's convenient that it's like this, but it's different then how it used to work, and I'm not sure if it's safe.

The documentation says it should throw, so either the documentation needs to be updated, or the Hashset needs to be fixed. https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1.getenumerator?view=net-6.0

Reproduction Steps

HashSet<int> set = new();
set.Add(1);
set.Add(2);

foreach (var x in set)
{
    set.Remove(x);
}

Expected behavior

Throws an invalid operation exception

Actual behavior

It works

Regression?

.Net 3.1 throws

Known Workarounds

Don't do it?

Configuration

No response

Other information

No response

ghost commented 2 years ago

Tagging subscribers to this area: @dotnet/area-system-collections See info in area-owners.md if you want to be subscribed.

Issue Details
### Description I found some code that was looping over a hashset, and removing. Hashset is not throwing when you remove while enumerating like it used to. It's convenient that it's like this, but it's different then how it used to work, and I'm not sure if it's safe. The documentation says it should throw, so either the documentation needs to be updated, or the Hashset needs to be fixed. https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1.getenumerator?view=net-6.0 ### Reproduction Steps ``` HashSet set = new(); set.Add(1); set.Add(2); foreach (var x in set) { set.Remove(x); } ``` ### Expected behavior Throws an invalid operation exception ### Actual behavior It works ### Regression? .Net 3.1 throws ### Known Workarounds Don't do it? ### Configuration _No response_ ### Other information _No response_
Author: wrexbe
Assignees: -
Labels: `area-System.Collections`
Milestone: -
stephentoub commented 2 years ago

Both HashSet and Dictionary have been improved to support removal during enumeration. The docs may just benefit from updating.

theodorzoulias commented 2 years ago

Related: Remove version increment from Dictionary<K,V>.Remove overloads

I was not aware that it affects the HashSet<T> collection too though.