May 8, 2011

Iterator Code Example in C#

Iterators are used to Iterator an User Defined Collection class using FOR EACH Loop
below is the code sample for it


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
{
    ArrayList PersonCol=new ArrayList();
    public void AddPerson(Person oP)
    {
        PersonCol.Add(oP);
    }
    public System.Collections.IEnumerator GetEnumerator()
    {
        for (int i = 0; i < PersonCol.Count; i++)
        {
            yield return PersonCol[i];
        }
    }


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