What does IEnumerator mean in simple form

Hello I would like to know what IENumerator means in a non-complex way.

IEnumerator is a fundamental interface for many of the collection types in C#.

Its a very simple (optionally Generic) interface which has two methods and a single property. MoveNext(), Reset() and Current.


Basically the main part of how it works is that in implementing an IEnumerator you just have to write some logic which when MoveNext() is called it sets Current to the next item in your sequence and then returns true if it was successful or false if it wasnt. This allows you to create types which can be enumerated … like lists or enumerators.


The specifics are here.


Another example would be thinking about a foreach loop. A foreach loop is just syntactic sugar around an IEnumerators MoveNext method.

When you compile your code this

foreach(var item in enumerable) { ... }

is equivalent to

while (enumerator.MoveNext()) { ... } 

Here is an example that spits out the Fibonacci sequence


If you want to know why they are used in Unitys Coroutines, there are plenty of places on the internet which explain that and equipped with an understanding of how IEnumerators work (above), it shouldnt be too hard to understand.

Unity: What is a Coroutine and why is there an IEnumerator / Habr

I also wrote my coroutine crash course here on UA which may help. Note I have a mirror version on github which displays better since UA has a somewhat messed up markdown rendering. Over there I actually added a few more details and a generic example coroutine scheduler implementation which may further help to understand what’s happening under the hood. Of course we don’t know how exactly Unity does implement and integrate the various wait types into the main game loop, but it’s somewhat similar.

in simple words you can slow down your execution.