Techopedia Explains Iterator
The iterator is based on a design pattern that provides a method to traverse the elements of a collection of items sequentially without exposing the underlying structure of the collection. It eliminates the tedious task of implementing the "IEnumerator" interface manually when creating collection classes that support the "foreach" statement. The Intermediate Language code necessary for implementing the methods and properties of the IEnumerator interface is generated by the compiler, which results in simpler syntax, reduced code size, and improvement in developer productivity.
In general, an iterator is similar to a database cursor in that it provides access to data elements in a collection, but does not perform iteration. An iterator can be implemented in C# as a method, operator, or get accessor. For example, an iterator can be used to traverse a collection of strings to display the content of each string in the collection.
An iterator is represented by the IEnumerator interface and is implemented by the compiler with the following methods:
- MoveNext: A method that advances to the next element of the collection and indicates the end of that collection
- Current: A property that fetches the value of the element currently being pointed to
- Dispose: Cleans up the iteration
GetEnumerator() is the default iterator method of the IEnumerable interface. This method can be implemented in the collection that contains the container class. The GetEnumerator() method is invoked on execution of the "foreach" statement, which uses the returned enumerator to iterate through values. The "yield return" statement is used within the iterator block to fetch an element of the collection. It also helps to position the current location such that execution starts from this location the next time it occurs. The "yield break" statement ends the iteration.