Information Technology Reference
In-Depth Information
Given a collection's enumerator, you should be able to simulate a
foreach
loop by cycling
through the items in the collection using the
MoveNext
and
Current
members. For example, you
know that arrays are enumerable, so the following code does
manually
what the
foreach
state-
ment does
automatically
. The output is the same as if it were in a
foreach
loop.
static void Main()
{
int[] MyArray = { 10, 11, 12, 13 }; // Create an array.
IEnumerator ie = MyArray.GetEnumerator(); // Get its enumerator.
while (ie.MoveNext() == true) // Move to the next item.
{
int i = (int) ie.Current; // Get the current item.
Console.WriteLine("{0}", i); // Write it out.
}
}