
When we want to reset the enumerator, we have to set the enumerator to its initial position: once again, this is before the first element of the collection. Let´s start by implementing the the constructor: we need the stack, and an index to point to the last element of the stack:Īs we have not started to iterate our index is pointing just beyond the last element of the stack, ready to position to the first element to iterate. IEnumerator: Reset, MoveNext, object IEnumerator.Current.IEnumerator extends from IEnumerator, and IDisposable so we have to implement all the methods of those interfaces: Object IEnumerator.Current => throw new NotImplementedException() Public T Current => throw new NotImplementedException() Having implemented IEnumerable, we need now to move on to implementing our Enumerator. Therefore we have methods for both the generic, and non generic enumerator. But IEnumerable extends from IEnumerable. Since our stack implementation uses generics, we want to implement IEnumerable. IEnumerator IEnumerable.GetEnumerator().When adding the interface we see we need to implement two methods that return an IEnumerator:
#What does an enumerator do how to
Take this Stack implementation – you can check here this post on how to implement a Stack in C# – and see if you notice some functionality lacking: Let´s see a simple example to understand why we may want to implement IEnumerable. IEnumerable is an interface that allows us to iterate over a collection it does so by exposing a single GetEnumerator() method, which in turn returns an IEnumerator: a simple interface that provides methods to access the current element in the collection, move to the next item, and reset back to the beginning of the collection.
