dotnet/wpf · error · InvalidOperationException

InvalidOperationException

Error message

InvalidOperationException

What it means

EmptyEnumerator is a singleton IEnumerator over zero items. Its Current getter always throws InvalidOperationException because there is no current element; callers must only use it after a false MoveNext/Reset contract — meaning Current should never legitimately be called.

Solutions

  1. Only access Current when MoveNext() returned true
  2. Use foreach instead of manual enumerator handling
  3. Check collection count before enumerating Current manually

Example fix

// before
var e = col.GetEnumerator(); var first = e.Current;
// after
var e = col.GetEnumerator();
if (e.MoveNext()) { var first = e.Current; }
Defensive patterns

Strategy: type-guard

Validate before calling

bool HasCurrent(IEnumerator e) => e.MoveNext(); // only then read Current

Type guard

bool TryGetCurrent(IEnumerator e, out object value) { value = null; if (e.MoveNext()) { value = e.Current; return true; } return false; }

Try / catch

try { var v = e.Current; } catch (InvalidOperationException) { /* empty enumerator; Current is undefined */ }

Prevention

When it happens

Trigger: Accessing the Current property of an empty collection's enumerator without a successful prior MoveNext(), or enumerating an empty custom collection exposed by WPF internals and reading Current defensively.

Common situations: Hand-rolled enumeration loops that read Current before/after MoveNext; code that assumes MoveNext returned true; reflection/debug tooling inspecting empty collections.

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


AI-assisted analysis of dotnet/wpf@81131a70a4 (2026-09-14). Data as JSON: /api/errors/c38f2ae16eaa83e4. Report an issue: GitHub.

Appendix: source

Thrown at src/Microsoft.DotNet.Wpf/src/PresentationFramework/MS/Internal/Controls/EmptyEnumerator.cs:55

        /// <summary>
        /// Does nothing.
        /// </summary>
        public void Reset() { }

        /// <summary>
        /// Returns false.
        /// </summary>
        /// <returns>false</returns>
        public bool MoveNext() { return false; }

        /// <summary>
        /// Returns null.
        /// </summary>
        public object Current
        {
            get
            {
                throw new InvalidOperationException();
            }
        }

        private static IEnumerator _instance;
    }
}

View on GitHub (pinned to 81131a70a4)