
So far, you’ve seen how iterator blocks are handy for creating enumerators. However, you can
also use them to generate the enumerable type as well. For example, suppose you want to iterate
through the first few powers of 2. You could do the following:
using System;
using System.Collections.Generic;
public class EntryPoint
{
static public IEnumerable<int> Powers( int from,
int to ) {
for( int i = from; i <= to; ++i ) {
yield return (int) Math.Pow( 2, i );
}
}
static void Main() {
IEnumerable<int> powers = Powers( 0, 16 );
foreach( int result in powers ) {
Console.WriteLine( result );
}
}
}
In this example, the compiler generates a single type that implements the ...