Saturday, June 20, 2026

C# Example of class that Implements IEnumerable interface

Step1. Create MyEnumerable class that implements IEnumerable. 

The MyEnumerator contains a collection type field and initializes it inside its constructor. It contains GetEnumerator method that returns IEnumerator type object.

Note that MyEnumerable uses MyEnumerator class inside GetEnumerator. Therefore, we create MyEnumerator class in step2.
class MyEnumerable : IEnumerable
{
    // Sample data inside our enumerable collection
    private readonly object[] _items;
    public MyEnumerable(object[] items)
    {
        _items = items;
    }

    public IEnumerator GetEnumerator()
    {
        // Pass the internal data to the enumerator
        return new MyEnumerator(_items);
    }
}
Step2. Create MyEnumerator class that implements IEnumerator. 

MyEnumerator class implements three members of IEnumerator - Current, MoveNext and Reset. The Current returns the current item from collection. MoveNext moves to next item in collection and Reset resets the iteration to the beginning item.
using System.Collections;

namespace Practicals;

class MyEnumerator : IEnumerator
{
    private readonly object[] _data;
    private int _position = -1;

    // Constructor to pass the data from the collection
    public MyEnumerator(object[] data)
    {
        _data = data;
    }

    // Returns the element at the current position
    public object Current
    {
        get
        {
            try
            {
                return _data[_position];
            }
            catch (IndexOutOfRangeException)
            {
                throw new InvalidOperationException(
                    "Enumeration has either not started or has already finished.");
            }
        }
    }

    // Advances the enumerator to the next element
    public bool MoveNext()
    {
        _position++;
        return (_position < _data.Length);
    }

    // Resets the pointer to its initial state
    public void Reset()
    {
        _position = -1;
    }
}
Step3. Program class is client or consumer class that consumes objects of MyEnumerable.
class Program
{
    static void Main(string[] args)
    {
        string[] colors = { "Red", "Green", "Pink", "Orange", "Yellow" };
        MyEnumerable collection = new MyEnumerable(colors);

        Console.WriteLine("Iterating using an Enumerator:");
        var enumeratorForCollection = collection.GetEnumerator();
        while (enumeratorForCollection.MoveNext())
        {
            Console.WriteLine(enumeratorForCollection.Current);
        }
        Console.WriteLine("----------------------------------");
        Console.WriteLine("Iterating using a foreach loop:");
        foreach (var item in collection)
        {
            Console.WriteLine(item);
        }
    }
}
OUTPUT
Iterating using an Enumerator:
Red
Green
Pink
Orange
Yellow
----------------------------------
Iterating using a foreach loop:
Red
Green
Pink
Orange
Yellow

No comments:

Post a Comment

Hot Topics