Search⌘ K
AI Features

Iterator: Implementation and Example

Explore how to implement the Iterator design pattern in C# by creating interfaces and concrete classes for iterating over collections. Understand how to traverse different data structures like lists and sorted binary trees using MoveNext and GetCurrent methods without exposing their internal forms.

Creating a console application

We’ll create a console application project. The first thing that we’ll add to this project is the following interface:

C#
namespace Iterator_Demo;
internal interface IIterator
{
bool MoveNext();
int GetCurrent();
}

This is our Iterator interface. It has two methods: MoveNext() and GetCurrent(). The MoveNext() method will iterate through each collection item and will update the pointer to the current item. It will return true if it’s possible to move to the next item, and false if there are no more items left.

GetCurrent() will retrieve the current value from the collection. For simplicity, we’re dealing with our example’s int ...