.NET Articles

C# IEnumerable interface with example


IEnumerable interface is used for iterate the collection using for loop. Let us see the example of how for loop works.

To execute foreach loop on object, object class must inherit from IEnumerable interface. Before rotating the loop, for loop executes the method IEnumerable.GetEnumerator (only once) of object which returns the object of type IEnumerator and t IEnumerator will have the methods such as “ MoveNext” to iterate the collection of objects based on incrementing the index item of collection.

Let us analyze our example of below code, ”Employees “is the class has an array object of class”Employee” which consists Employee Name and Father Name. Our target is to iterate this Employee Array of Employees class using forloop. See below complete code with output then we discuss in depth about execution flow.

using System;
using System.Collections;
using System.Collections.Generic;
   
public class Employee
{

    public Employee(string name, string fatherName)
    {
        Name = name;
        FatherName = fatherName;
    }
    public string Name { get; set; }
    public string FatherName { get; set; }
}
public class Employees:IEnumerable
{
    private Employee[] _employees;
    public Employees(Employee[] employees )
    {
        _employees = employees;
    }
    
    public IEnumerator GetEnumerator()
    {
        return new EmployeeEnum(_employees);
    }
}

public class EmployeeEnum:IEnumerator
{
    int i = -1;
    private Employee[] _employees;

    public EmployeeEnum(Employee[] Employees)
    {
        _employees = Employees;
    }
    public object Current
    {
        get { return _employees[i]; }
    }

    public bool MoveNext()
    {
        i = i + 1;
        return i< _employees.Length ;
   
    }

    public void Reset()
    {
        throw new NotImplementedException();
    }
}


class Program
{
    static void Main(string[] args)
    {
        Employee[] _employee = new Employee[3] { new Employee("Ram", "Gopal"), new Employee("Ramesh", "Raja"), new Employee("Chanti", "Mohan") };

        Employees _employeess = new Employees(_employee);

        foreach (Employee emp in _employeess)
        {
            Console.WriteLine("Employee Name: " + emp.Name + " , Father Name: " + emp.FatherName);
        }

        Console.ReadLine();
    }
   
}

        

Output:

          Employee Name: Ram , Father Name: Gopal
          Employee Name: Ramesh , Father Name: Raja
          Employee Name: Chanti, Father Name: Mohan
        

Analysis in depth:

When we use foreach loop as shown below,

foreach (Employee emp in _employeess)

_employeess is the object of the class Employees.

When For loop starts executes, it initially calls the IEnumerable.GetEnumerator of Employees class and GetEnumerator method returns the type IEnumerator. So the class which inherited from IEnumerator interface will have the methods for iterate for loop, in our example GetEnumerator returns the object EmployeeEnum. Then onwards every time in foreach loop makes the call to “MoveNext” method of interface(IEnumerator) and “MoveNext” method have logic to increase the index and returns Boolean that whether index has not exceeded the array maximum length.

            public bool MoveNext()
            {
                i = i + 1;
                return i< _employees.Length ;   
            }
        

After MoveNext() method execution, immediately calls the “Current” Method of interface(IEnumerator) which will return the current Item from the collection based on index set by “MoveNext”. In our example Current returns the Employee class.

            public object Current
            {
                get { return _employees[i]; 
            }