C# Language Using yield to create an IEnumerator when implementing IEnumerable


Example

The IEnumerable<T> interface has a single method, GetEnumerator(), which returns an IEnumerator<T>.

While the yield keyword can be used to directly create an IEnumerable<T>, it can also be used in exactly the same way to create an IEnumerator<T>. The only thing that changes is the return type of the method.

This can be useful if we want to create our own class which implements IEnumerable<T>:

public class PrintingEnumerable<T> : IEnumerable<T>
{
    private IEnumerable<T> _wrapped;

    public PrintingEnumerable(IEnumerable<T> wrapped)
    {
        _wrapped = wrapped;
    }

    // This method returns an IEnumerator<T>, rather than an IEnumerable<T>
    // But the yield syntax and usage is identical.
    public IEnumerator<T> GetEnumerator()
    {
        foreach(var item in _wrapped)
        {
            Console.WriteLine("Yielding: " + item);
            yield return item;
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

(Note that this particular example is just illustrative, and could be more cleanly implemented with a single iterator method returning an IEnumerable<T>.)