Iterators

  • Thread starter Thread starter Alvin
  • Start date Start date
In the current spec, iterators are just methods that return IEnumerator,
IEnumerable, IEnumerator<T>, or IEnumerable<T> and use the yield
keywords(last I heard, the final spec will be using yield break and yield
return). So you should be able to have as many enumerators as you wish. The
default call, GetEnumerator(), is in itself just another method.
 
Alvin said:
Will it be possible to have more than one Iterator in a type?

Absolutely. Because it's so easy to write an iterators now (or rather,
soon), hopefully more people will use common iteration patterns in their
code. With the current version of C#, writing an enumerator requires a
certain amount of tribal knowledge.

Given a class called Racers with three exposed iterators:

class Racers: IEnumerable<string>
{
string [] _grid = {"Mickey", "Ali", "Kenzie"};
public IEnumerator<string> GetEnumerator()
{
foreach (string racer in _grid)
yield racer;
}
public IEnumerable<string> Grid
{
get
{
foreach (string racer in _grid)
yield racer;
}
}
public IEnumerable<string> BottomUp()
{
for (int i = _grid.Length - 1; i >= 0; --i)
yield _grid;
}
}

You can enumeratoe in a variety of ways:

static void Main(string[] args)
{
Racers racers = new Racers();
// Calls GetEnumerator
foreach (string r in racers)
Console.WriteLine(r);
// Calls Grid
foreach (string r in racers.Grid)
Console.WriteLine(r);
// Calls BottomUp
foreach (string r in racers.BottomUp())
Console.WriteLine(r);
Console.ReadLine();
}
 
Back
Top