Java Iterator vs C# IEnumerable

It's not used very often, but the analogy is the IEnumerator<T> interface:

var enumerator = labels.GetEnumerator();

.NET's IEnumerator differs from Java's Iterator with the following:

  • Iterator after construction is pointing at the first element of the collection (or, for an empty collection, is invalid and hasNext will return false immediately), IEnumerator points initially before the first element of the collection (for an empty collection MoveNext will return false)
  • Iterator has hasNext method, while for IEnumerator you verify the result of MoveNext method
  • Iterator has next method, while for IEnumerator you also use MoveNext
  • Iterator's next returns the next element, while with IEnumerator you use Current property after calling MoveNext
  • Iterator in Java has remove method which allows you to remove elements from the underlying collection. There is no equivalent in IEnumerator

So for Java you'd iterate with something like this:

it = labels.iterator();
while (it.hasNext())
{
    elem = it.next();
}

While in C#:

en = labels.GetEnumerator();
while (en.MoveNext())
{
    elem = en.Current;
}

Usually, having labels as a collection (which always implements IEnumerable<T>) you just use it directly:

foreach (var label in labels)
{
    //...
}

And of course, you can store IEnumerable<T> for later use (names referring to your example):

IEnumerable<Label> it = labels;

Beware, that IEnumerable<T> is lazy, just like Iterator in Java.

You can also easily obtain a snapshot of a collection like this (again, it refers to your example, better name could be chosen):

IEnumerable<Label> it = labels.ToArray();
// or Label[] it = labels.ToArray();
// or better: var it = labels.ToArray();

Tags:

C#

Java

Iterator