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.
IEnumerator
interface solve those problems?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".
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.
IEnumerator is the base interface for all non-generic enumerators. Its generic equivalent is the System.
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 .
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?
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