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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With