* Remove unnecessarion _version++ from a few places
In some collection types, resizing the backing store can affect in-flight enumerations, e.g. growing a queue will cause the implementation to relayout the elements contiguously from the beginning, which will invalidate indices stored in enumerators. But for `List<T>` and `Stack<T>`, changing the backing array doesn't impact the index stored in an enumerator, nor does it impact what the enumerator will enumerate, so these operations needn't invalidate the enumerators. `List<T>`'s `set_Capacity` and `TrimExcess` already didn't update the version, but its `EnsureCapacity` did, and `Stack<T>`'s `TrimExcess` and `EnsureCapacity` both updated the version. This change just removes those unnecessary increments.
* Add a Stack.TrimExcess test
if (_size < threshold)
{
Array.Resize(ref _array, _size);
- _version++;
}
}
if (_array.Length < capacity)
{
Grow(capacity);
- _version++;
}
return _array.Length;
{
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
- public void EnsureCapacity_RequestingLargerCapacity_DoesInvalidateEnumeration(int count)
+ public void EnsureCapacity_RequestingLargerCapacity_DoesNotInvalidateEnumeration(int count)
{
List<T> list = GenericListFactory(count);
IEnumerator<T> copiedListEnumerator = new List<T>(list).GetEnumerator();
list.EnsureCapacity(capacity + 1);
- Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
+ enumerator.MoveNext();
}
[Fact]
}
}
+ [Fact]
+ public void Stack_Generic_TrimExcess_DoesNotInvalidateEnumeration()
+ {
+ Stack<T> stack = GenericStackFactory(10);
+ stack.EnsureCapacity(100);
+
+ IEnumerator<T> enumerator = stack.GetEnumerator();
+ stack.TrimExcess();
+ enumerator.MoveNext();
+ }
+
#endregion
[Theory]
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
- public void Stack_Generic_EnsureCapacity_RequestingLargerCapacity_DoesInvalidateEnumeration(int count)
+ public void Stack_Generic_EnsureCapacity_RequestingLargerCapacity_DoesNotInvalidateEnumeration(int count)
{
Stack<T> stack = GenericStackFactory(count);
IEnumerator<T> copiedEnumerator = new List<T>(stack).GetEnumerator();
stack.EnsureCapacity(count + 1);
- Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
+ enumerator.MoveNext();
}
[Fact]
if (_items.Length < capacity)
{
Grow(capacity);
- _version++;
}
return _items.Length;