IEnumerable<T> Interface

Namespace: System.Collections.Generic
Assembly: System.Runtime.dll
Supports iteration over a generic collection.

Syntax

public interface IEnumerable<out T> : IEnumerable

Type Parameters

Name Description
T The type of objects to enumerate. The out keyword indicates that this type parameter is covariant.

Inheritance

System.Object
System.Collections.IEnumerable
System.Collections.Generic.IEnumerable<T>

Members

Methods

Name Description
GetEnumerator() Returns an enumerator that iterates through the collection.

GetEnumerator()

IEnumerator<T> GetEnumerator();

Returns: An IEnumerator<T> that can be used to iterate through the collection.

Remarks

The IEnumerable<T> interface is the base interface for all generic collections that can be enumerated. It provides a way to iterate over the elements of a collection without exposing the underlying implementation of the collection.

The GetEnumerator method is the only method defined by the IEnumerable<T> interface. It returns an enumerator object that implements the IEnumerator<T> interface. The enumerator object can be used to iterate through the elements of the collection by calling its MoveNext and Current properties.

The IEnumerable<T> interface is implicitly implemented by any generic collection class that implements the ICollection<T> or IList<T> interfaces.

Example

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        List<string> names = new List<string> { "Alice", "Bob", "Charlie" };

        // Using foreach loop, which implicitly uses IEnumerable<T>
        foreach (string name in names)
        {
            Console.WriteLine(name);
        }

        // Explicitly getting an enumerator
        IEnumerator<string> enumerator = names.GetEnumerator();
        try
        {
            while (enumerator.MoveNext())
            {
                string currentName = enumerator.Current;
                Console.WriteLine($"Explicit: {currentName}");
            }
        }
        finally
        {
            if (enumerator != null)
            {
                ((IDisposable)enumerator).Dispose();
            }
        }
    }
}