Can anyone explain IEnumerable and IEnumerator to me?
for example, when to use it over foreach? what's the difference between IEnumerable and IEnumerator? Why do we need to use it?
Can anyone explain IEnumerable and IEnumerator to me?
for example, when to use it over foreach? what's the difference between IEnumerable and IEnumerator? Why do we need to use it?
An understanding of the Iterator pattern will be helpful for you. I recommend reading the same.
Iterator Pattern
At a high level the iterator pattern can be used to provide a standard way of iterating through collections of any type. We have 3 participants in the iterator pattern, the actual collection (client), the aggregator and the iterator. The aggregate is an interface/abstract class that has a method that returns an iterator. Iterator is an interface/abstract class that has methods allowing us to iterate through a collection.
In order to implement the pattern we first need to implement an iterator to produce a concrete that can iterate over the concerned collection (client) Then the collection (client) implements the aggregator to return an instance of the above iterator.
Here is the UML diagram
So basically in c#, IEnumerable is the abstract aggregate and IEnumerator is the abstract Iterator. IEnumerable has a single method GetEnumerator that is responsible for creating an instance of IEnumerator of the desired type. Collections like Lists implement the IEnumerable.
Example. Lets suppose that we have a method
getPermutations(inputString)
that returns all the permutations of a string and that the method returns an instance ofIEnumerable<string>
In order to count the number of permutations we could do something like the below.
The c# compiler more or less converts the above to
If you have any questions please don't hesitate to ask.
Think of enumerable objects as of lists, stacks, trees.