Explain the iterator pattern in .NET

ASP.NetServer Side ProgrammingProgramming

The iterator pattern is used to loop over the elements in a collection and is implemented using the IEnumerator interface. It defines the basic low-level protocol through which elements in a collection are traversed—or enumerated. This is done in a forward-only manner.

Here's the IEnumerator interface in C#.

public interface IEnumerator{
   bool MoveNext();
   object Current { get; }
   void Reset();
}
  • MoveNext advances the current element or "cursor" to the next position, returning false if there are no more elements in the collection.

  • Current returns the element at the current position (usually cast from object to a more specific type). MoveNext must be called before retrieving the first element—this is to allow for an empty collection.

  • The Reset method, if implemented, moves back to the start, allowing the collection to be enumerated again.

Collections do not usually implement enumerators; instead, they provide enumerators, via the interface IEnumerable −

public interface IEnumerable{
   IEnumerator GetEnumerator();
}

This interface defines a single method that returns an enumerator. This provides flexibility in that the iteration logic can be handed off to another class. It also means that several consumers can enumerate the collection at once without interfering with one another. You can think of IEnumerable as "IEnumeratorProvider,” and it is the most basic interface that collection classes implement.

The following example illustrates low-level use of IEnumerable and IEnumerator −

Example

string s = "Hello";
// Because string implements IEnumerable, we can call GetEnumerator():
IEnumerator rator = s.GetEnumerator();
while (rator.MoveNext()){
   char c = (char) rator.Current;
   Console.Write (c + ".");
}

Output

H.e.l.l.o.

However, it's rare to call methods on enumerators directly in this manner because C# provides a syntactic shortcut: the foreach statement. Here's the same example rewritten using foreach

string s = "Hello"; // The String class implements IEnumerable
foreach (char c in s)
Console.Write (c + ".");

IEnumerable<T> and IEnumerator<T>

IEnumerator and IEnumerable are nearly always implemented in conjunction with their extended generic versions −

public interface IEnumerator<T> : IEnumerator, IDisposable{
   T Current { get; }
}
public interface IEnumerable<T> : IEnumerable{
   IEnumerator<T> GetEnumerator();
}
raja
Published on 19-May-2021 08:19:42
Advertisements