Iterators

Iteration refers to repeatedly performing some process. Therefore, an iterator is the component that allows this iteration to occur. In development terms, iterators provide a means to iterate over a collection. As discussed in Chapters 7 and 20, this is typically accomplished by using a For Each loop.

Most collections in the .NET framework implement the IEnumerable or IEnumerable(Of T) interface. This interface provides the GetEnumerator method which returns an IEnumerator, which performs the actual iteration for you. Again, all of this is covered in Chapters 7 and 19. The point here is that when you use a For Each loop and specify a collection, the compiler automatically calls the GetEnumerator method implemented by the class.

Providing custom or additional iterators required you to create customized classes that implemented IEnumerator or IEnumerator(Of T). Creating enumerators required a little bit of work because you had to implement several methods that provide the iteration logic.

To help alleviate some of these issues and provide a more concise way to provide custom iterators or control the flow of your code, Microsoft created Iterator and Yield. The Iterator modifier and Yield operator were first introduced in the same CTP add-on that introduced Async and Await. They are now part of version 4.5 of the .NET framework.

The Core Concept

It will quickly become apparent why Microsoft released both Async/Await and Iterator/Yield at the same time for both the Visual ...

Get Professional Visual Basic 2012 and .NET 4.5 Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.