title: Writing custom IEnumerator<T> with iterators
body: <p>How can I write a custom <code>IEnumerator&lt;T&gt;</code> implementation which needs to maintain some state and still get to use iterator blocks to simplify it? The best I can come up with is something like this:</p>
  
  <pre><code>public class MyEnumerator&lt;T&gt; : IEnumerator&lt;T&gt; {
      private IEnumerator&lt;T&gt; _enumerator;
      public int Position {get; private set;} // or some other custom properties
  
      public MyEnumerator() {
          Position = 0;
          _enumerator = MakeEnumerator();
      }
  
      private IEnumerator&lt;T&gt; MakeEnumerator() {
          // yield return something depending on Position
      } 
  
      public bool MoveNext() {
          bool res = _enumerator.MoveNext();
          if (res) Position++;
          return res;
      }
  
      // delegate Reset and Current to _enumerator as well
  }
  
  public class MyCollection&lt;T&gt; : IEnumerable&lt;T&gt; {
  
      IEnumerator&lt;T&gt; IEnumerable&lt;T&gt;.GetEnumerator() {
          return GetEnumerator();
      }
  
      public MyEnumerator&lt;T&gt; GetEnumerator() {
          return new MyEnumerator&lt;T&gt;();
      }
  
      ...
  }
  </code></pre>