The generic version of IEnumerable provides a way to make enumeration type-safe. Type mis-matches will show up at compile time rather than run time. Here is a code example.
using System;
using System.Collections;
using System.Collections.Generic;
public class Person
{
public Person(string fName, string lName)
{
this.firstName = fName;
this.lastName = lname;
}
public string firstName;
public string lastName;
}
//
//Make the class People enumerable on Person
//
public class People : IEnumerable<Person>
{
private Person[] people;
public People(Person[] pArray)
{
people = new Person[pArray.length];
for (int i = 0; i < pArray.length; i++)
{
people[i] = pArray[i];
}
}
//Implement GetEnumerator for IEnumerable<Person>
//This implementation works when the variable that holds
//the required values is enumerable
public IEnumerator<Person> GetEnumerator()
{
foreach (Person p in people)
{
yeild return p;
}
}
//Implement GetEnumerator for the IEnumerable interface that is
//implied by IEnumerable<Person>.
//Use explicit implementation.
IEnumerator IEnumerable.GetEnumerator()
{
foreach (Person p in people)
{
yeild return p;
}
}
}