We know, if we change a collection in a foreach
loop, the following exception is thrown:
InvalidOperationException: Collection was modified; enumeration operation may not execute.
But there is a method that behaves differently: List<T>.Sort(Comparison<T>)
.
For example (dotnetfiddle.net):
List<int> list = new List<int> { 2, 1 } ;
foreach (int i in list)
{
//list.Sort(Comparer<int>.Default); // InvalidOperationException
//list.Sort(); // InvalidOperationException
list.Sort((a, b) => a.CompareTo(b)); // No exception
Console.WriteLine(i);
}
According to the referencesource.microsoft.com we can see that there is no version increment in this particular method, while there is one in the method above:
public void Sort(int index, int count, IComparer<T> comparer) {
...
_version++;
}
Version is incremented also in all other methods that modify the list.
My questions are:
As I remember I've posted this bug report to Microsoft about 8-9 years ago, but it was declined. And now I cannot find it anymore.
It was a bug, that's why it is fixed in latest source code.
https://github.com/dotnet/coreclr/blob/master/src/mscorlib/src/System/Collections/Generic/List.cs#L986
public void Sort(Comparison<T> comparison) {
if( comparison == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison);
}
Contract.EndContractBlock();
if (_size > 1) {
ArraySortHelper<T>.Sort(_items, 0, _size, comparison);
}
_version++;
}
There may be many similar bugs, unless someone reports and it is considered as very risky, they remain as they are not priorities.
Don't worry, there was similar bug in List.ForEach
, that would not throw Modified Exception, I did report it and they declined, but in subsequent version it was fixed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With