TheChaseMan's Frenetic SoapBox

Always looking for better ways to do things...

Implementing IEnumerator

Ever wanted to create an enumerable class? Implementing IEnumerator and IEnumerable can do the trick.
 

using System;
using System.Collections;

public class Person {
   
public Person(string name, int age) {
        Name = name;
        Age = age;
    }
   
public string Name;
   
public int Age;
}

public class People : IEnumerable {
   
private Person[] _people;
   
public People() {
        _people = new Person[3]
        {
           
new Person("Bob", 30),
           
new Person("Jim", 31),
           
new Person("Sue", 29),
        };
    }

   private class PeopleEnum : IEnumerator {
       
    public Person[] _people;
   
       
int position = -1;

           
public PeopleEnum(Person[] list) {
                _people = list;
            }

           
public bool MoveNext() {
                position++;
               
return (position < _people.Length);
            }

           
public void Reset() {position = -1;}

            public object Current {
               
get {
                   
try {
                       
return _people[position];
                    }
                   
catch (IndexOutOfRangeException) {
                       
throw new InvalidOperationException();
                    }
                }
            }
        }

    
public IEnumerator GetEnumerator() {
           
return new PeopleEnum(_people);
       }
}


class App {
    [STAThread]
   
static void Main(string[] args) {
        People people = new People();
       
foreach(Person p in people)
            Console.WriteLine(p.Name + "\t\t" + p.Age);
        }
}


Digg!

posted on Tuesday, March 09, 2004 2:45 PM

Feedback

No comments posted yet.