Data Structures and Algorithms with Object-Oriented Design Patterns in C#
next up previous contents index

GetEnumerator Method

As discussed in Section gif, the GetEnumerator method of a Container returns an IEnumerator. An enumerator is meant to be used like this:

Stack stack = new StackAsArray(57);
stack.Push(3);
stack.Push(1);
stack.Push(4);
IEnumerator e = stack.GetEnumerator();
while (e.MoveNext())
{
    Object obj = e.Current;
    Console.WriteLine(obj);
}
This code creates an instance of the StackAsArray class and assigns it to the variable stack. Next, several ints are pushed onto the stack. Finally, an enumerator is used to systematically print out all of the objects in the stack.

Program gif defines GetEnumerator method of the StackAsArray class. The GetEnumerator method returns a new instance of the private class StackAsArray.Enumerator that implements the IEnumerator interface (lines 5-32).

   program5449
Program: StackAsArray class GetEnumerator method.

The Enumerator class has two fields, stack and position. The stack field refers to the stack whose elements are being enumerated. The position field is used to keep track of the position in the array of the current object.

The MoveNext method is called in the loop termination test of the while loop given above. The purpose of MoveNext method is to advance the enumerator to the next object in the stack. The enumerator resets the position to -1 and returns false when there are no more elements. Clearly, the running time of MoveNext is O(1).

The Current property provides a get accessor that returns the current object. It returns the object in the stack specified by the position field provided that the value of the position field is non-negative. Otherwise, it throws a InvalidOperationException exception. Clearly, the running time of Current is also O(1).


next up previous contents index

Bruno Copyright © 2001 by Bruno R. Preiss, P.Eng. All rights reserved.