C# IEnumerable Interface

implementation of IEnumerable Interface in C#

IEnumerable is the implementation of the iterator pattern and is used to give the ability to iterate a class without knowing its internal structure. This Interface exposes the enumerator, which supports a simple iteration over a collection of a specified type. When a class implements IEnumerable, it can be enumerated. This means you can use a foreach block to iterate over that type. In C# all collections implements this interface.

Here is example of foreach loop iterates over the IEnumerable<int>.

class Program
{
    static void Main()
    {
	IEnumerable<int> result = from value in Enumerable.Range(1, 6)select value;
				
	foreach (int value in result)
	{
	    Console.WriteLine(value);
	}

    }
}

This interface is used with Yield Return key phrase, You can find more about it here.

Implementation

In this example, Test Class contains array of Test items. WE need to provide implementation of  GetEnumerator() that returns IEnemerator.

class Test : IEnumerable
    {
        Test[] Items = null;
        int freeIndex = 0;
        public string Name { get; set; }
        public int Id { get; set; }

        public Test()
        {
            Items = new Test[5];
        }

    public void Add(Test item)
    {
        Items[freeIndex] = item;
        freeIndex++;
    }

//implementation of IEnumerator
    public IEnumerator GetEnumerator()
    {
        foreach (object o in Items)
        {
            if(o == null)
                break;
            yield return o;
        }
    }
    }
    class Program
        {
            public static void Main(String[] args)
            {
                Test t1 = new Test();
                t1.Name = "Bob";
                t1.Id = 0;

                Test t2 = new Test();
                t2.Name = "John";
                t2.Id= 1;

                Test myList = new Test();
                myList.Add(t1);
                myList.Add(t2);

//Now we can use for each loop
                foreach (Test obj in myList)
                {
                   Console.WriteLine("Name: "+ obj.Name + "Id:- "+ obj.Id);
                }
                Console.ReadLine();
            }
        }

 

This is just basic introduction to this subject, for each loop is a syntax sugar. There is much more happening in the background. This post is starting point to this subject, in next article I’ll cover more advanced topics. Stay Awesome!

 

 

Author: indiedevart

Indie Games Developer

3 thoughts on “C# IEnumerable Interface”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s