C# IEnumerable and IEnumerator

C# Code Snippets_ IEnumerable And IEnumerator
Share:

About

In this code snippet, we will take a look at the IEnumerator and IEnumerable in C#.

Making an object enumerable will allow us to iterate over it with something like the foreach loop. IEnumerable is an interface that specifies what has to be implemented to make an object iterable(an object that can be iterated over). For an object to be iterable it has to have a GetEnumerator() method that returns an object of type IEnumerator.

Here we will be using the yield keyword. It essentially creates a temporary List<> to which we will add our elements. A List<> already has an enumerator implemented. So that’s why we won’t be making our own enumerator here. You need to do that if you make a custom collection and want to make it iterable. For more information see Microsofts documentation.

Let’s have a look at the code below to see how to make an object enumerable.

Once you implement the interface you can just press ctrl + .  select “implement interface” and IntelliSense will automatically make the required GetEnumerator() method.

Code:

Resulting output:

Share:

Leave a Reply

Your email address will not be published.

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger