Starting and stopping an iterator

Sometimes you want to stop and start an iterator and continue from where you last stopped. For example, in the code below, we ask for 2 names, stop and then ask for 3 more names.


static void Main(string[] args)
{
NameSource nameSource = new NameSource();

// get 2 names
foreach(string s in nameSource.GetNames(2))
{
Console.Out.WriteLine(”{0}”, s);
}

// get 3 more names
foreach (string s in nameSource.GetNames(3))
{
Console.Out.WriteLine(”{0}”, s);
}

Console.ReadLine();
}

To have the iterator know where it left off, we simple store the current place in the iteration in state variable. For example, in the code below we store the index of the current item being iterated over in the state variable ‘current’:


public class NameSource
{
///


/// Keeps track of the names already returned and starts off where it left off.
///

public IEnumerable GetNames(int amount)
{
for(int i = 0; i < amount; i++)
{
yield return strings[current++];
}
}

///


/// initialize state variable ‘current’
///

private int current = 0;
private static readonly string[] strings =
new string[] { “ankur”, “buster”, “ricardo”, “jerome”, “constantine”};
}

Actually, the article title is a misnomer. We’re not actually starting and stopping the same iterator, we’re creating two iterators that are referencing the same state variable. This makes it appear as one continuous iteration.

Leave a Reply