IEnumerable interface exposes the enumerator, which supports a simple iteration over a non-generic collection.
using System;
using System.Collections;
public class Employee
{
public Employee(string fName, string lName)
{
this.firstName = fName;
this.lastName = lName;
}
public string firstName;
public string lastName;
}
public class EmployeeCollection : IEnumerable
{
private Employee[] _people;
public EmployeeCollection(Employee[] pArray)
{
_people = new Employee[pArray.Length];
for (int i = 0; i < pArray.Length; i++)
{
_people[i] = pArray[i];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator) GetEnumerator();
}
public EmployeeCollectionEnum GetEnumerator()
{
return new EmployeeCollectionEnum(_people);
}
}
public class EmployeeCollectionEnum : IEnumerator
{
public Employee[] _people;
int position = -1;
public EmployeeCollectionEnum(Employee[] list)
{
_people = list;
}
public bool MoveNext()
{
position++;
return (position < _people.Length);
}
public void Reset()
{
position = -1;
}
object IEnumerator.Current
{
get
{
return Current;
}
}
public Employee Current
{
get
{
try
{
return _people[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
}
class App
{
static void Main()
{
Employee[] peopleArray = new Employee[3]
{
new Employee("A", "D"),
new Employee("B", "E"),
new Employee("C", "F"),
};
EmployeeCollection peopleList = new EmployeeCollection(peopleArray);
foreach (Employee p in peopleList)
Console.WriteLine(p.firstName + " " + p.lastName);
}
}
Related examples in the same category