Wednesday, January 31, 2007

Writing generic enumerators in C# (.NET 2.0)

The MSDN documentation is sort of lacking on how to write up a class that implements an Enumerator that can return a specific type of an object using Generics. So I wrote up a test class and here it is for your programming convenience.
using System;
using System.Threading;
using System.Collections;
using System.Collections.Generic;

public class MyEnumerable <T> : IEnumerable<T>, IEnumerator<T>
{
    public MyEnumerable( List<T> items ) {
        this.items = items;
    }

    public IEnumerator<T> GetEnumerator() 
    {
        return this;
    }

    IEnumerator IEnumerable.GetEnumerator() 
    {
        return GetEnumerator();
    }

    public T Current 
    {
        get { return items[index]; }
    }
    
    object IEnumerator.Current 
    {
        get { return Current; }
    }
    
    public bool MoveNext() 
    {
         index++;
        if( index < items.Count ) 
        {
            return true;
        } else 
        {
            return false;
        }
    }

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

    
    public void Dispose() 
    {
       
    }       
      
    private int index = -1;
    private List<T> items;
}

public class GenericEnumeratorsTest
{
    static void Main() 
    {
        List<string> stringList = new List<string>();
        stringList.Add("Tyrannosaurus");
        stringList.Add("Amargasaurus");
        stringList.Add("Mamenchisaurus");
        stringList.Add("Deinonychus");
        stringList.Add("Compsognathus");

        MyEnumerable<string> stringEnumerator = new MyEnumerable<string>( stringList );
        
        System.Console.WriteLine("using foreach");
        foreach(string s in stringEnumerator)
        {
            System.Console.WriteLine(stringEnumerator.Current);
        }
        
        System.Console.WriteLine("");
        System.Console.WriteLine("using MoveNext");
        stringEnumerator.Reset();
        while(stringEnumerator.MoveNext())
        {
            System.Console.WriteLine(stringEnumerator.Current);
        }
                
        System.Console.ReadKey();
        
    }
}

No comments: