Definition - What does Iterator mean?
An iterator is used to enable consumers of a container class, containing a collection or array, to traverse the collection using the "foreach" statement in a simpler manner. It is used with strongly typed collection classes to iterate complex data structures like binary trees, which require recursive traversal and maintain the iteration state through the recursion. The concept of iterator is also used in implementing deferred execution in LINQ queries.
Techopedia explains Iterator
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