Iterators

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Alvin

    #1

    Iterators

    Will it be possible to have more than one Iterator in a type?
  • Daniel O'Connell

    #2
    Re: Iterators

    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" <alvinbj@hotmai l.com> wrote in message
    news:e728582f.0 311200753.7df5c e67@posting.goo gle.com...[color=blue]
    > Will it be possible to have more than one Iterator in a type?[/color]


    Comment

    • Mickey Williams

      #3
      Re: Iterators

      "Alvin" <alvinbj@hotmai l.com> wrote in message
      news:e728582f.0 311200753.7df5c e67@posting.goo gle.com...[color=blue]
      > Will it be possible to have more than one Iterator in a type?[/color]

      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<str ing>
      {
      string [] _grid = {"Mickey", "Ali", "Kenzie"};
      public IEnumerator<str ing> GetEnumerator()
      {
      foreach (string racer in _grid)
      yield racer;
      }
      public IEnumerable<str ing> Grid
      {
      get
      {
      foreach (string racer in _grid)
      yield racer;
      }
      }
      public IEnumerable<str ing> BottomUp()
      {
      for (int i = _grid.Length - 1; i >= 0; --i)
      yield _grid[i];
      }
      }

      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.WriteLi ne(r);
      // Calls Grid
      foreach (string r in racers.Grid)
      Console.WriteLi ne(r);
      // Calls BottomUp
      foreach (string r in racers.BottomUp ())
      Console.WriteLi ne(r);
      Console.ReadLin e();
      }

      --
      Mickey Williams
      Author, "Microsoft Visual C# .NET Core Reference", MS Press




      Comment

      Working...