IEnumerable Interface

System.Collections

Summary

Exposes the enumerator, which supports a simple iteration over a non-generic collection.

Interface Members

Remarks

The IEnumerable interface is the base interface for all generic and non-generic collections in the .NET Framework. It allows a collection to be enumerated (iterated over) using a foreach statement or by manually using an IEnumerator.

Classes that implement IEnumerable must provide an implementation for the GetEnumerator method, which returns an object that implements the IEnumerator interface. The IEnumerator interface provides methods for moving through the collection (MoveNext), resetting the position to the beginning (Reset), and retrieving the current element (Current).

Example

C#
VB.NET
using System;
using System.Collections;

public class MyCollection : IEnumerable
{
    private string[] _items = { "Apple", "Banana", "Cherry" };

    public IEnumerator GetEnumerator()
    {
        return _items.GetEnumerator();
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        MyCollection fruits = new MyCollection();

        foreach (string fruit in fruits)
        {
            Console.WriteLine(fruit);
        }
    }
}
Imports System
Imports System.Collections

Public Class MyCollection : Implements IEnumerable
    Private _items() As String = { "Apple", "Banana", "Cherry" }

    Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
        Return _items.GetEnumerator()
    End Function
End Class

Public Class Program
    Public Shared Sub Main(args() As String)
        Dim fruits As MyCollection = New MyCollection()

        For Each fruit As String In fruits
            Console.WriteLine(fruit)
        Next
    End Sub
End Class