Sunday, April 13, 2008

Looping Through Your Class

You may want others who use your class to be able to loop through it. To make this possible your class has to use the interface IEnumerable and implement IEnumerable.GetEnumerator() method.
public class Family : IEnumerable
{
    private List<string> familyMembers = new List<string>()
            {
                //Collection Initializer
                "Mother", "Father", "Patty", "Bob"
            };

    public IEnumerator GetEnumerator()
    {
        foreach (string member in familyMembers)
        {
            if (member == "Mother")
                yield return "Claudia";
            else if (member == "Father")
                yield return "Phillip";
            else
                yield return member;
        }
    }
}
In your GetEnumerator function you can customize the way data is returned when a consumer does a foreach on your class.
Family family = new Family();
foreach (string member in family)
{
    Console.WriteLine(member);
}
More Info: MSDN: Iterators