SIGN UP MEMBER LOGIN:    
ARTICLE

Enumerators in C#

Posted by Prasad H Articles | C# Language September 18, 2001
Sample example shows you how to use enumerators in C#.
Reader Level:

Description 

This article explains how to implement enumerators in C#.

We know how to use foreach for built-in types of C#.But how do we Use for objects of our class. For

class
Employee
{
}

how do we use foreach for the objects of Employee. 

Step#1:

To foreach construct for user-defined classes the first thing we have to do is Imlplement the interface IEnumerable. Then Ienumerable interface has a method called GetEnumerator() which returns an object of IEnumerator. 

Step#2:

Next we have to implement IEnumerator interface.The IEnumerator has 3 methods namely Reset(),Current(),MoveNext().After we code for the 3 methods we are able to use foreach() for our UDC(User Defined Classes).

Step#3:

How does foreach works when we use foreach() construct it first Calls MoveNext() if it returns true then the loop is continued to the value from the Current() method call.Reset() is used to set the Enumerator to begining position. 

Let's run through a coding sample which will make things clear:

The source code has 2 classes namely Employee,Employees. Employee class hold information about each Employee. The Employees class hold array of Employee objects.

Source Code Explanation:

  1. Create Employees class object

    Employees EmpList=
    new Employees();

  2. Create Employee class objects

    Employee e1=
    new Employee(1,"Employee#1",1250.75);
    Employee e2=
    new Employee(2,"Employee#2",1275.85);

  3. Add Employee object to Employees class object

    EmpList.AddEmployee(e1);
    EmpList.AddEmployee(e2);

  4. foreach(Employee emp in EmpList)
    {
    Console.WriteLine(emp);
    }

    When this statement is executed it will call the GetEnumerator() method of the Employees class to get the IEnumerator object.Then it calls the MoveNext() method since it returns true it calls the Current() method and return the Employee object.which is printed.this same sequence is repeated for 2nd Employee.During the third time call MoveNext() returns false and it exits the foreach construct. 

  5. To clearly get the underhood of Enumerator() see the code below which does the above sequence:

    IEnumerator EmpEnumerator=EmpList.GetEnumerator(); //Getting the Enumerator
    EmpEnumerator.Reset(); //Position at the Beginning
    While(EmpEnumerator.MoveNext()) //Till not finished do print
    {
    Console.WriteLine((Employee)EmpEnumerator.Current);
    }
    }

Complete Source Code:

// Source Code starts here
using System;
using System.Collections;
class Employee
{
private int Id;
private string Name;
private double Salary;
public Employee(int id,string name,double salary)
{
this.Id=id;
this.Name=name;
this.Salary=salary;
}
public int ID
{
get
{
return this.Id;
}
}
public override string ToString()
{
return "Id:" + this.Id.ToString() + "\nName:" + Name + "\nSalary:" + Salary.ToString();
}
}
class Employees:IEnumerable,IEnumerator
{
ArrayList EmpList=
new ArrayList();
private int Position=-1;
public void AddEmployee(Employee oEmp)
{
EmpList.Add(oEmp);
}
/* Needed since Implementing IEnumerable*/
public IEnumerator GetEnumerator()
{
return (IEnumerator)this;
}
/* Needed since Implementing IEnumerator*/
public bool MoveNext()
{
if(Position<EmpList.Count-1)
{
++Position;
return true;
}
return false;
}
public void Reset()
{
Position=-1;
}
public object Current
{
get
{
return EmpList[Position];
}
}
public static void Main()
{
Employees EmpList=
new Employees();
Employee e1=
new Employee(1,"Employee#1",1250.75);
Employee e2=
new Employee(2,"Employee#2",1275.85);
EmpList.AddEmployee(e1);
EmpList.AddEmployee(e2);
Console.WriteLine("Enumerating Employees using foreach");
foreach(Employee emp in EmpList)
{
Console.WriteLine(emp);
}
Console.WriteLine("\nEnumerating Employee Creating object of IEnumerator");
IEnumerator EmpEnumerator=EmpList.GetEnumerator();
EmpEnumerator.Reset();
while(EmpEnumerator.MoveNext())
{
Console.WriteLine((Employee)EmpEnumerator.Current);
}
}
}
// Source Code Ends here

Login to add your contents and source code to this article
share this article :
post comment
 

Thank you!

Posted by Vijay c Apr 04, 2012

it's easy to understand Enumerators for me. thank for share it.

Posted by daoo daoo Jan 06, 2011

It's dangerous to make the class its own enumerator. The expected behaviour of GetEnumerator is for each enumerator returned on an instance to have its own cursor, so multiple enumerators over an IEnumerable can exist and work independently (that's why enumerators were invented). With your implementation, all calls to GetEnumerator on an instance return the *same* enumerator. That means that a client with an enumerator of an instance can find their cursor moving unexpectedly, because some other client is moving the cursor in what they think is a different enumerator but which under the hood is really the same one.

Posted by Tim Rowe Feb 17, 2009
Nevron Gauge for SharePoint
Become a Sponsor
PREMIUM SPONSORS
  • The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor