SoFunction
Updated on 2025-03-01

The difference between IEnumerator<T> and IEnumerable in C#

In C#,IEnumerator<T>andIEnumerableIt is an interface used to implement iteration. The difference is their function and how they are used.

IEnumerableThe interface represents an enumerable collection, which defines a methodGetEnumerator(), this method returns an implementationIEnumeratorObject of the interface. This means that the type is implementedIEnumerableInterface, which can provide an iterator for accessing elements in a collection in order.IEnumerableThe interface is read-only, it can only support forward iteration and cannot modify elements in the collection.

IEnumerator<T>The interface is the iterator interface of the generic version, which is inherited fromIEnumeratorInterface, and added aCurrentAttribute, used to get the element at the current position in the collection.IEnumerator<T>The interface defines the following methods and properties:

  • bool MoveNext(): Move the iterator to the next element of the collection, and return if it is successfully moved to the next element.true, otherwise returnfalse
  • void Reset(): Reset the iterator to the start position of the collection.
  • T Current: Get the element at the current position in the collection.

By implementingIEnumerator<T>Interface, which can create an iterator that can iterate over accessing elements in a generic collection.

Here is an example that demonstratesIEnumerableandIEnumerator<T>Usage and difference:

using System;
using ;
using ;

public class MyCollection&lt;T&gt; : IEnumerable&lt;T&gt;
{
    private List&lt;T&gt; items = new List&lt;T&gt;();

    public void Add(T item)
    {
        (item);
    }

    public IEnumerator&lt;T&gt; GetEnumerator()
    {
        return new MyEnumerator&lt;T&gt;(items);
    }

    IEnumerator ()
    {
        return GetEnumerator();
    }
}

public class MyEnumerator&lt;T&gt; : IEnumerator&lt;T&gt;
{
    private List&lt;T&gt; items;
    private int currentIndex = -1;

    public MyEnumerator(List&lt;T&gt; items)
    {
         = items;
    }

    public bool MoveNext()
    {
        currentIndex++;
        return currentIndex &lt; ;
    }

    public void Reset()
    {
        currentIndex = -1;
    }

    public T Current
    {
        get { return items[currentIndex]; }
    }

    object 
    {
        get { return Current; }
    }

    public void Dispose()
    {
        // No implementation required    }
}

public class Program
{
    public static void Main()
    {
        MyCollection&lt;int&gt; collection = new MyCollection&lt;int&gt;();
        (1);
        (2);
        (3);

        // Use foreach to traverse the collection        ("Use foreach to traverse the collection:");
        foreach (int item in collection)
        {
            (item);
        }

        ();

        // Use an iterator to manually traverse the collection        ("Manually traverse the collection using an iterator:");
        IEnumerator&lt;int&gt; enumerator = ();
        while (())
        {
            int item = ;
            (item);
        }
    }
}

In this example, we define a name calledMyCollection<T>generic collection class, it implementsIEnumerable<T>Interface. existMyCollection<T>In the class, we useList<T>Storing elements in the collection and implementingGetEnumeratorMethod, return an implementationIEnumerator<T>Iterator of the interface.

We also defined a name calledMyEnumerator<T>The generic iterator class, which implementsIEnumerator<T>Interface. existMyEnumerator<T>In the class, we use an indexcurrentIndexTrack the current location and implementMoveNextmethod,ResetMethods andCurrentAttributes.

existMainIn the method, we created aMyCollection<int>A collection instance of type and several elements are added to it. Then, we useforeachLoops and iterators manually traverse the collection and output the value of each element.

By implementingIEnumerable<T>andIEnumerator<T>Interface, we can implement iterable collections in C# and useforeachLoop or manual iterator to access elements in the collection.IEnumerator<T>Provides more powerful features because it allows direct access to the current element without the need for type conversion.

This is the end of this article about the difference between IEnumerator<T> and IEnumerable in C#. For more related C# IEnumerator<T>, please search for my previous articles or continue browsing the related articles below. IEnumerable, IEnumerable content. IEnumerable will be more supported by everyone in the future!