Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerator Purpose

Tags:

c#

ienumerator

I don't quite understand what the use of IEnumerator from the C# Collections is. What is it used for and why should it be used?

I tried looking online at http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.aspx but that article doesn't make much sense. The reason I ask is in Unity3d Game Engine, it's used along with the yield function. I am trying to make sense of the reason for the use of IEnumerator.

like image 563
RoR Avatar asked Oct 28 '10 19:10

RoR


3 Answers

The IEnumerator interface, when implemented by a class allows it to be iterated through using the built-in foreach syntax.

In the class that needs to be iterated for the IEnumerator interface defines a method signature for the GetEnumerator function that controls looping through the object.

public IEnumerator<OrderLine> GetEnumerator()
    {
        for (int i=0;i<maxItems;i++) 
        {
            yield return item[i];
        }
    }

As you can see in this example, the yield statement lets you return control to the caller without losing its place in the enumeration. Control will be passed back to the line after the yield statement when the caller hits the next increment of the foreach loop.

like image 190
JohnFx Avatar answered Sep 22 '22 05:09

JohnFx


You rarely use IEnumerator explicitly, but there are a lot of extension methods that work with it, as well as the foreach. All of the collections implement it, and it's an example of the Iterator pattern.

like image 25
veljkoz Avatar answered Sep 21 '22 05:09

veljkoz


It's quite simply just an interface which allows objects to perform operations for easily iterating over collections. You could use it to create objects which iterate over a custom collection with a foreach construct or similiar syntax.

like image 41
Adam Naylor Avatar answered Sep 22 '22 05:09

Adam Naylor