May 8, 2011

Enumerator code Example in C#

Enumerators are used to Iterate an User Defined Collection class using FOR EACH Loop by implementing Enumerable,IEnumerator Interfaces.
Below is the code sample 

using System;
using System.Collections;
class Person
{
    private int Id;
    private string Name;
    
    public Person(int id, string name)
    {
        this.Id = id;
        this.Name = name;
       
    }
    public int ID
    {
        get
        {
            return Id;
        }
    }
    public string NAME
    {
        get
        {
            return Name;
        }
    }
  
}


class Personcollection:IEnumerable,IEnumerator
{
    ArrayList PersonCol=new ArrayList();
    int Position = -1;
    public void AddPerson(Person oP)
    {
        PersonCol.Add(oP);
    }




    /* Needed since Implementing IEnumerable*/
    public IEnumerator GetEnumerator()
    {
        return (IEnumerator)this;
    }
    /* Needed since Implementing IEnumerator*/
    public bool MoveNext()
    {
        if (Position < PersonCol.Count - 1)
        {
            ++Position;
            return true;
        }
        return false;
    }
    public void Reset()
    {
        Position = -1;
    }
    public object Current
    {
        get
        {
            return PersonCol[Position];
        }
    } 






public static void Main()
{
    Personcollection PList = new Personcollection();
    Person p1 = new Person(1, "test1");
    Person p2 = new Person(2, "test2");
    PList.AddPerson(p1);
    PList.AddPerson(p2);
   
    Console.WriteLine("Iterate User Defined Person Collection using for each loop");
    foreach (Person objp in PList)
    {
        Console.WriteLine("ID: " +objp.ID);
        Console.WriteLine("NAME: " +objp.NAME);
    }

}
}

No comments:

Post a Comment