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.
IEnumerable<int> numbers = new[] { 1, 2, 3 }; foreach (int n in numbers) { Console.WriteLine(n); }
Try it
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.
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
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
foreachneeds only a pattern. The compiler usesIEnumerable<T>when available but also accepts any type with a publicGetEnumerator()method that returns something withMoveNext()andCurrent; this is howList<T>avoids boxing its struct enumerator.- Deferred execution. LINQ operators and
yieldmethods 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()orToArray()once when you need the data repeatedly. Analyzers warn about this ("possible multiple enumeration"). - No
Countproperty.Enumerable.Count()checks whether the source is also anICollection<T>and readsCountin O(1); otherwise it walks everything. UseAny()to test for emptiness. - Parameter type. Accept
IEnumerable<T>when you only read the items once,IReadOnlyList<T>when you needCountand an indexer,ICollection<T>when you add or remove. - Return type. Returning
IEnumerable<T>hides the concrete collection but, if the instance is really aList<T>, callers can still cast it. ReturnIReadOnlyList<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 withawait foreach.