Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Collections

The IEnumerable<T> interface

Reference for C# IEnumerable<T>: the interface behind foreach and LINQ, how to implement it with yield, deferred execution, multiple enumeration and when to use it.

IEnumerable<T> (namespace System.Collections.Generic) represents a sequence of values that you can walk through from start to end. It has a single method, GetEnumerator(), which returns an IEnumerator<T>. Every foreach loop, every LINQ operator and almost every collection in .NET is built on it: arrays, List<T>, Dictionary<K,V>, strings (as IEnumerable<char>) and iterator methods that use yield return.

It says nothing about size, order guarantees or random access. That is its strength as a parameter type: a method that takes IEnumerable<T> accepts any of those sources. It is also why a sequence may be lazy, computed only as you ask for each item, or even infinite.

C#
IEnumerable<int> numbers = new[] { 1, 2, 3 };
foreach (int n in numbers)
{
    Console.WriteLine(n);
}

Try it

C# Implementing a sequence with yield

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Deferred execution and multiple enumeration

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

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

public interface IEnumerable
{
    IEnumerator GetEnumerator();
}
Member Description
GetEnumerator() Returns a fresh enumerator positioned before the first element.
out T IEnumerable<T> is covariant: an IEnumerable<string> can be used where an IEnumerable<object> is expected.

Returns: an IEnumerator<T> that you drive with MoveNext() and Current (or let foreach do it).

Errors: none from the interface itself. Individual sources may throw when enumerated, for example InvalidOperationException if a List<T> is changed during a foreach.

Usage notes

  • foreach needs only a pattern. The compiler uses IEnumerable<T> when available but also accepts any type with a public GetEnumerator() method that returns something with MoveNext() and Current; this is how List<T> avoids boxing its struct enumerator.
  • Deferred execution. LINQ operators and yield methods run when you iterate, not when you call them. Exceptions from argument validation inside an iterator method also appear late; split into a checking method and a private iterator if early errors matter.
  • Multiple enumeration. Each pass restarts the work. For queries over databases, files or expensive computations this means doing it twice. Call ToList() or ToArray() once when you need the data repeatedly. Analyzers warn about this ("possible multiple enumeration").
  • No Count property. Enumerable.Count() checks whether the source is also an ICollection<T> and reads Count in O(1); otherwise it walks everything. Use Any() to test for emptiness.
  • Parameter type. Accept IEnumerable<T> when you only read the items once, IReadOnlyList<T> when you need Count and an indexer, ICollection<T> when you add or remove.
  • Return type. Returning IEnumerable<T> hides the concrete collection but, if the instance is really a List<T>, callers can still cast it. Return IReadOnlyList<T> or a copy when that matters.
  • Strings are IEnumerable<char>, so "abc".Reverse() and "abc".Count() compile through LINQ.
  • Async version: IAsyncEnumerable<T> is consumed with await foreach.