Information Technology Reference
In-Depth Information
Example Using IEnumerable and IEnumerator
Putting the MyColors and ColorEnumerator examples together, you can add a class called
Program with a Main method that creates an instance of MyColors and uses it in a foreach loop.
using System;
using System.Collections;
namespace ColorCollectionEnumerator
{
class ColorEnumerator: IEnumerator
{
string[] Colors;
int Position = -1;
public ColorEnumerator(string[] theColors) // Constructor
{
Colors = new string[theColors.Length];
for (int i = 0; i < theColors.Length; i++)
Colors[i] = theColors[i];
}
public object Current // Current
{ get { return Colors[Position]; } }
public bool MoveNext() // MoveNext
{
if (Position < Colors.Length - 1)
{ Position++; return true; }
else
return false;
}
Search WWH ::




Custom Search