Member-only story

Enumerations in C# with IEnumerable & IEnumerator — explained

Stefan Schranz
3 min readMar 30, 2021

C#, just like a lot of modern programming languages, makes it very easy to iterate collections. But how exactly do these parts work under the hood?

First, let’s see a short example:

public static void Main()
{
var simpleList = new List<String>(){ "Hello", "to", "Medium" };
foreach (var item in simpleList)
{
Console.WriteLine(item);
}
}
=> Output:
Hello
to
Medium

Nice and simple. You just use a foreach loop to iterate through the collection, and it works just like you expect.

Now, one might be just satisfied with this, and that’s absolutely fine. Things like these are made to abstract some of the hard parts away from the developer who is just looking to get things done.
However, if you are interested in how things work under the hood, there is a lot to uncover, and a lot to learn as well.

The key to understanding iterations are within two interface:

IEnumerable and IEnumerator

Let’s take a look at these two.

IEnumerable:

In short, an IEnumerable as well as it’s generic counterpart IEnumerable<T> represents an iterable collection…

--

--

Stefan Schranz
Stefan Schranz

Written by Stefan Schranz

26 year old full stack software developer from Germany - Enthusiatic about C#, .Net and Cloud — Visit me at https://dotschranz.net/

Responses (1)