C# language feature:
applies to
benefit
how to use
using System.Collections;
IEnumerable
method.return
statement in the loop with yeild
keyword.example:
static class Iterator_Example
{
// 1) don't forget to include `using System.Collections;`
// 2) Implement `IEnumerable` method.
public static System.Collections.IEnumerable Powers(int number, int maxPower)
{
int counter = 0;
int result = 1;
while (counter++ < maxPower) // 3) create a loop block which
{
result = result * number;
yield return result; // returns an iteration preceded by yield keyword
// note that each iteration "remembers state" i.e. counter and result variables
// also note the return statement pauses/yeilds for the next call
}
}
}
class Use_of_Iterator_Example
{
public void go_iterate(){
foreach (var currentIteration in Iterator_Example.Powers(3, 4))
{
System.Console.WriteLine(currentIteration); // 3, 9, 27, 81
}
}
}