dotnet / dotnet/dotnet-api-docs

Hashset Remove is not throwing on enumeration

Open
#8,177 4 comments 1 reaction 0 assignees View on GitHub
area-System.Collections doc-update Pri3
Dominant language
C#
Stars
949
Forks
1.7k
Avg merge
3d 27m
Merged PRs (30d)
49

Description

### 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 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_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.