IEnumerable Interface

Namespace: System.Collections

The IEnumerable interface is the base interface for all generic and non-generic collections in the .NET Framework. It provides a way to iterate over a collection, typically by a for-each loop (or For Each in Visual Basic). This interface has a single method, GetEnumerator, which returns an enumerator for the collection.

Definition

The IEnumerable interface is defined in the System.Collections namespace.

public interface IEnumerable
{
    IEnumerator GetEnumerator();
}

Members

Purpose and Usage

The primary purpose of IEnumerable is to enable iteration over a sequence of elements. Any class that implements IEnumerable can be used in a foreach statement. This abstraction allows you to write code that works with a wide variety of collection types without needing to know their specific implementation details.

C# Syntax Example

using System;
using System.Collections;
using System.Collections.Generic;

// Assume this class implements IEnumerable
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 collection = new MyCollection();

        Console.WriteLine("Iterating through MyCollection:");
        foreach (string item in collection)
        {
            Console.WriteLine(item);
        }
    }
}
Note: For generic collections, it is highly recommended to use the IEnumerable<T> interface instead of the non-generic IEnumerable. IEnumerable<T> provides type safety and performance benefits.

IEnumerable<T>

The generic version, IEnumerable<T>, inherits from the non-generic IEnumerable and adds a generic GetEnumerator method that returns an IEnumerator<T>.

public interface IEnumerable<out T> : IEnumerable
{
    new IEnumerator<T> GetEnumerator();
}

The out keyword indicates that T is a covariant type parameter, meaning you can use a type with a lower-ranked generic type argument than specified.

Related Interfaces