Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reason for creating IEnumerator?

Tags:

IEnumerator contains MoveNext(), Reset() and Current as its members. Now assume that I have moved these methods and property to IEnumerable interface and removed GetEnumerator() method and IEnumerator interface.

Now, the object of the class which implements IEnumerable will be able to access the methods and the property and hence can be iterated upon.

  • Why was the above approach not followed and the problems I will face if I follow it?
  • How does presence of IEnumerator interface solve those problems?
like image 610
zizouraj Avatar asked Sep 09 '14 11:09

zizouraj


People also ask

What is the use of IEnumerator?

Here is the documentation on IEnumerator . They are used to get the values of lists, where the length is not necessarily known ahead of time (even though it could be). The word comes from enumerate , which means "to count off or name one by one".

Where do we use IEnumerator in C#?

IEnumerable interface should be implemented in order to use your custom objects in the form of a collection (series of values or objects). Which means you can use it directly with the foreach statement. IEnumerable interface has a method called GetEnumerator() which returns an object implemented IEnumerator.

Is IEnumerator an interface?

IEnumerator is the base interface for all non-generic enumerators. Its generic equivalent is the System.

What is the difference between IEnumerator and IEnumerable?

An IEnumerator is a thing that can enumerate: it has the Current property and the MoveNext and Reset methods (which in . NET code you probably won't call explicitly, though you could). An IEnumerable is a thing that can be enumerated...which simply means that it has a GetEnumerator method that returns an IEnumerator .


1 Answers

An iterator contains separate state to the collection: it contains a cursor for where you are within the collection. As such, there has to be a separate object to represent that extra state, a way to get that object, and operations on that object - hence IEnumerator (and IEnumerator<T>), GetEnumerator(), and the iterator members.

Imagine if we didn't have the separate state, and then we wrote:

var list = new List<int> { 1, 2, 3 };  foreach (var x in list) {     foreach (var y in list)     {          Console.WriteLine("{0} {1}", x, y);     } } 

That should print "1 1", "1 2", "1 3", "2 1" etc... but without any extra state, how could it "know" the two different positions of the two loops?

like image 153
Jon Skeet Avatar answered Sep 20 '22 16:09

Jon Skeet