What is an Enumerator, Iterator, IEnumerable and IEnumerator and relation with yield return keyword
Hello guys, from what I've read, an enumerator is what get returns from an IEnumerable, which is itself a sequence of element that can be iterated over.
So basically, an enumerable gives us a series of element. Then on these series of element, one by one, we can get an "enumerator" which will allow us to access each one of them one at a time. The enumerator uses methods to manually control the looping process. However, an enumerator can also return an iterator which does the exact same job behind the scenes, it's just syntax sugar; using the command
yield return
yield return
, we return an iterator which behind the scenes will just methods like .MoveNext() from an enumerator.
It's still a bit unclear in my head, I believed I mixed things up, would really appreciate if someone can add to what I've said and correct me where I went wrong please.
Also, one thing, consider the following code:
foreach (int i in ProduceEvenNumbers(9)){ Console.Write(i); Console.Write(" ");}// Output: 0 2 4 6 8IEnumerable<int> ProduceEvenNumbers(int upto){ for (int i = 0; i <= upto; i += 2) { yield return i; }}
foreach (int i in ProduceEvenNumbers(9)){ Console.Write(i); Console.Write(" ");}// Output: 0 2 4 6 8IEnumerable<int> ProduceEvenNumbers(int upto){ for (int i = 0; i <= upto; i += 2) { yield return i; }}
the IEnumerable is an interface, right? We can use interface as data types? why use interface as data types?