You cannot, because you made your code surface a single enumerator, the IMO error itself. The best version for me:
class T : IEnumerable<int> { public IEnumerator<int> GetEnumerator() { int i = 0; while(i < 5) { yield return i; i++; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } }
The compiler will create the correct devices to achieve this using separate counters.
If you are not writing for .NET 1.1, then if you find that you are writing the enumarator manually, there is a very good chance that you can do this with difficulty, and you are mistaken as a bonus.
If you really must do this hard:
class T : IEnumerable<int> { public T() { } public IEnumerator<int> GetEnumerator() { return new TEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private class TEnumerator : IEnumerator<int> { private int position = -1; public int Current { get { return position; } } object IEnumerator.Current { get { return Current; } } void IDisposable.Dispose() {} public bool MoveNext() { position++; return (position < 5); } public void Reset() { position = -1; } } }
The value here is that different instances of TEnumerator allow you to iterate the same T separately.
source share