C# language feature:

  • Iterators

applies to

  • collections

benefit

  • Allows a standard way to traverse of a collection of objects. Facilitate iterator pattern.

how to use

  • 1) Include using System.Collections;
  • 2) Implement IEnumerable method.
  • 3) Create a loop block which returns an iteration value. Precede the 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
            }
        }
    }