C# langauge: Enumerators and iterators

The enumerators and iterators in general are used to move after the elements of the collection, we will start by discussing the enumerations.


Enumerator class is used for calculations, it works similarly to foreach instructions, however, the enumerator can be said to be a more low-level version.

For example, a high-level type of iteration by the word “programmer” in foreach looks like this:

And low-level looks like this:

First, we start to iterate from the first character or “p” as it is a “char” type so we must use the MoveNext() method in the while statement to be able to pass to the next characters if any exists.


As the enumeration of subsequent elements of the collection is not very convenient and readable using the GetEnumerator() method, so something like iterators was created, thanks to them we do not need to use such methods as eg MoveNext() or GetEnumerator(), iterators use only yield return words used to return values from a loop. Below is a simple example:

In order to be able to use the yield return statement, the method must be of the type IEnumerable in this method simply we throw in a string and return after one character to the foreach statement, i.e. char type.

However, what does the yield return statement means at all?

While the return word means “here is the value you asked for this method”, the yield return statement means “Here is the next item that you requested from this enumerator”.

yield break

As you might guess, the yield break statement is supposed to finish the iterator’s work prematurely. Example:

I added only one instruction, when it will have the value 5, the method will stop returning subsequent values, as a result the program will return the string “p r o g r”.

Let’s now write our own method using the yield return statement which extracts the last three numbers from the table in which there are ten digits.

This content also you can find on my steemit blog: https://steemit.com/programming/@slawas/c-langauge-enumerators-and-iterators

And on medium: https://medium.com/@sawomirkowalski/c-langauge-enumerators-and-iterators-4b7e8e236a94

If that post was useful for you share it with your friends :)

Post a comment

Notify about