What is IEnumerable in C#? with code

IEnumerable interface is used when we want to ITERATE among our collection classes using a FOREACH loop. 

In C#, IEnumerable is an interface that represents a sequence of objects that can be enumerated. It is defined in the System.Collections namespace. The IEnumerable interface provides a standard way to iterate over a collection using a foreach loop or LINQ operators.

Here's an example that demonstrates IEnumerable:

using System; using System.Collections; using System.Collections.Generic; public class MyClass : IEnumerable<string> { private List<string> items = new List<string>(); public void AddItem(string item) { items.Add(item); } public IEnumerator<string> GetEnumerator() { return items.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class Program { public static void Main() { MyClass myClass = new MyClass(); myClass.AddItem("Apple"); myClass.AddItem("Banana"); myClass.AddItem("Orange"); foreach (string item in myClass) { Console.WriteLine(item); } } }

In the above example:

  • The MyClass class implements the IEnumerable<string> interface, specifying that it can be enumerated over a sequence of strings.
  • The class has an internal list of strings (items) and a AddItem method to add items to the list.
  • The GetEnumerator method is implemented to return an enumerator (iterator) for the internal list.
  • The class also includes an explicit implementation of IEnumerable.GetEnumerator to satisfy the non-generic IEnumerable interface.
  • In the Main method, an instance of MyClass is created, and items are added to it.
  • The foreach loop iterates over the instance of MyClass, implicitly calling the GetEnumerator method and printing each item.

By implementing IEnumerable, you enable the ability to iterate over the elements of a collection using the foreach loop or LINQ operators. The interface defines a single method, GetEnumerator(), that returns an IEnumerator or IEnumerator<T>. This enumerator allows for iterating over the collection by retrieving each element one by one.

Using IEnumerable provides a standard way to work with collections and enables compatibility with LINQ query operations, making it easier to query, filter, and manipulate data in a collection.

Post a Comment

Previous Post Next Post