Using yield to create an IEnumeratorT when implementing IEnumerableT

suggest change

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>.)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Yield Keyword:
* Using yield to create an IEnumeratorT when implementing IEnumerableT

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
117 Yield Keyword
127 Caching
135 Pointers
147 C# Script