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!