Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

IEnumerator — the non-generic enumerator interface

System.Collections.IEnumerator describes a cursor for sequentially reading elements. It exposes MoveNext(), an object-valued Current, and Reset(); it is not a collection and does not guarantee IDisposable support.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

public interface IEnumerator
{
    object Current { get; }
    bool MoveNext();
    void Reset();
}

System.Collections.IEnumerator describes the state of one traversal through a collection. By contrast, System.Collections.IEnumerable exposes GetEnumerator(), which returns such a cursor. In ordinary code, prefer foreach, which hides manual enumerator management. The interface is available in .NET 10 and does not require preview language features.

Initially, the cursor is before the first element. Call MoveNext() and read Current only when the result is true. A result of false means the end; subsequent calls also return false unless the enumerator is reset. Current is undefined before the first successful advance and after completion—do not assume a particular value or exception.

Current is a read-only property of type object: recovering a specific type may require a cast, and value-type values are boxed. The generic System.Collections.Generic.IEnumerator<T> exposes a T-typed Current and inherits from both IEnumerator and IDisposable. Non-generic IEnumerator itself does not inherit from IDisposable; during manual iteration, dispose the enumerator if its object implements that interface.

Reset() is intended to restore the position before the first element, but it may throw NotSupportedException; it exists mainly for COM interoperability. To repeat a traversal, normally obtain a new enumerator. Do not assume collection changes during iteration are supported: they may invalidate the enumerator. The interface provides neither thread safety nor collection-modification operations.

Examples

using System;
using System.Collections;

internal static class Program
{
    private static void Main()
    {
        IEnumerable values = new string[] { "Ada", "Lin" };
        IEnumerator cursor = values.GetEnumerator();

        try
        {
            while (cursor.MoveNext())
            {
                string value = (string)cursor.Current;
                Console.WriteLine(value);
            }
        }
        finally
        {
            (cursor as IDisposable)?.Dispose();
        }
    }
}

Result

Ada
Lin

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources