I am trying to implement a caching mechanism for enumerating collections safely, and I am checking if all modifications of the built-in collections are triggering an InvalidOperationException
to be thrown by their respective enumerators. I noticed that in the .NET Core platform the Dictionary.Remove
and Dictionary.Clear
methods are not triggering this exception. Is this a bug or a feature?
Example with Remove
:
var dictionary = new Dictionary<int, string>();
dictionary.Add(1, "Hello");
dictionary.Add(2, "World");
foreach (var entry in dictionary)
{
var removed = dictionary.Remove(entry.Key);
Console.WriteLine($"{entry} removed: {removed}");
}
Console.WriteLine($"Count: {dictionary.Count}");
Output:
[1, Hello] removed: True
[2, World] removed: True
Count: 0
Example with Clear
:
var dictionary = new Dictionary<int, string>();
dictionary.Add(1, "Hello");
dictionary.Add(2, "World");
foreach (var entry in dictionary)
{
Console.WriteLine(entry);
dictionary.Clear();
}
Console.WriteLine($"Count: {dictionary.Count}");
Output:
[1, Hello]
Count: 0
The expected exception is:
InvalidOperationException: Collection was modified; enumeration operation may not execute.
...as is thrown by the method Add
, and by the same methods in .NET Framework.
.NET Core 3.0.0, C# 8, VS 2019 16.3.1, Windows 10