dotnet/wpf · error
SR.EnumeratorReachedEnd
Error message
SR.EnumeratorReachedEnd
What it means
The enumerator's Current property throws InvalidOperationException with SR.EnumeratorReachedEnd when Current is read after MoveNext returned false (index past the last element). Once iteration has finished there is no valid current element, so the sentinel check raises instead of returning a stale or null value.
Solutions
- Only read Current when the preceding MoveNext() returned true
- Call Reset() (or get a fresh enumerator) before iterating again
- Capture the last item inside the loop instead of reading Current afterward
Example fix
// before
while (e.MoveNext()) { }
var last = e.Current;
// after
object last = null;
while (e.MoveNext()) { last = e.Current; } Defensive patterns
Strategy: try-catch
Try / catch
object last = null; while (enumerator.MoveNext()) { last = enumerator.Current; } /* do not read enumerator.Current after the loop */ Prevention
- Read Current only when MoveNext() returned true
- Capture values inside the loop instead of after exhaustion
- Call Reset() or obtain a fresh enumerator to iterate again
When it happens
Trigger: Continuing to read Current after MoveNext() returned false, e.g. a loop that reads Current unconditionally one extra time, or caching the enumerator and reading Current after a completed pass.
Common situations: while(true) loops with a broken termination check, reusing a finished enumerator for a 'last element' access, or LINQ operators applied to an already-exhausted enumerator reference.
Understand the failure class
Background: "Invalid state transition" errors: "status must be X, actually Y", "already rejected/charging/uninstalled", "cannot ... while running" — what they mean when a library rejects your call — this error's family across 31 libraries.
Related errors
- SR.EnumeratorNotStarted
- Collection_CopyTo_ArrayCannotBeMultidimensional
- Collection_CopyTo_ArrayCannotBeMultidimensional
- Collection_CopyTo_IndexGreaterThanOrEqualToArrayLength
- Collection_CopyTo_IndexGreaterThanOrEqualToArrayLength
AI-assisted analysis of dotnet/wpf@81131a70a4 (2026-09-14).
Data as JSON: /api/errors/474dd917583d8bb9.
Report an issue: GitHub.
Appendix: source
Thrown at src/Microsoft.DotNet.Wpf/src/PresentationFramework/MS/Internal/documents/ContentElementCollection.cs:347
_currentElement = _collection;
_index = _collection.Size;
return (false);
}
}
public TItem Current
{
get
{
if (_currentElement == _collection)
{
if (_index == -1)
{
throw new InvalidOperationException(SR.EnumeratorNotStarted);
}
else
{
throw new InvalidOperationException(SR.EnumeratorReachedEnd);
}
}
return (TItem)_currentElement;
}
}
/// <summary>
/// <see cref="IEnumerator.Current"/>
/// </summary>
object IEnumerator.Current
{
get
{
return this.Current;
}
}
View on GitHub (pinned to 81131a70a4)