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.