Search⌘ K
AI Features

IEnumerable Interface

Explore how the IEnumerable and IEnumerable<T> interfaces work to support iteration over collections using the foreach loop in C#. Understand the roles of IEnumerator and IEnumerator<T> interfaces, learn to implement custom enumerable collections, and use the yield keyword to simplify iteration logic in your custom types.

While standard for loops require explicit iteration logic, the foreach loop relies on an underlying structural contract to traverse a collection. To allow a custom type to be iterated using a foreach loop, that type must implement the IEnumerable interface.

Multiple interface implementation
Multiple interface implementation

The IEnumerable<T> interface

Non-generic collections implement the IEnumerable interface, while generic collections use the generic version, IEnumerable<T>. The IEnumerable<T> interface is derived from IEnumerable, and therefore a class implementing the generic version must also implement the non-generic version.

The interfaces are defined as follows:

public interface IEnumerable
{
IEnumerator GetEnumerator();
}
public interface IEnumerable<out T> : IEnumerable
{
new IEnumerator<T> GetEnumerator();
}
Definitions of the IEnumerable interfaces
  • Lines 1–4: We define the non-generic interface which requires a method to return an IEnumerator.

  • Lines 6–9: We define the generic interface which inherits from the non-generic version and returns a generic IEnumerator<T>.

When implementing these, we need two GetEnumerator methods, and the one from the non-generic IEnumerable must be implemented explicitly. To understand how the iteration actually occurs, we must examine the object returned by these methods.

The IEnumerator

...