Understanding and Using `IEnumerable` in C#: Iterating Through Collections

Learn about the `IEnumerable` interface in C# and its crucial role in working with collections of objects. This tutorial explains its functionality, demonstrates implementing `IEnumerable` in custom classes, and highlights how it enables efficient iteration and powerful features like LINQ (Language Integrated Query).



Understanding `IEnumerable` in C#

Introduction

In C#, `IEnumerable` is a fundamental interface used to work with collections of objects. It provides a standard way to iterate (loop through) the items in a collection, enhancing code readability and enabling powerful features like LINQ (Language Integrated Query).

`IEnumerable` Interface

The `IEnumerable` interface is defined in the `System.Collections` namespace. It has a single method:

`IEnumerable` Interface Definition

public interface IEnumerable {
    IEnumerator GetEnumerator();
}

The `GetEnumerator()` method returns an `IEnumerator`, which is used to actually iterate through the collection.

Example: Iterating Through a Custom Collection

This example demonstrates a custom `StudentCollection` class that implements `IEnumerable` to allow iteration over a list of `Student` objects.

Example: Custom Collection with `IEnumerable`

using System;
using System.Collections;
using System.Collections.Generic;

public class Student {
    public string Name { get; set; }
    public int Age { get; set; }
}

public class StudentCollection : IEnumerable {
    private List<Student> students = new List<Student>();

    public void Add(Student student) {
        students.Add(student);
    }

    public IEnumerator GetEnumerator() {
        return students.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator() {
        return GetEnumerator();
    }
}

class Program {
    static void Main(string[] args) {
        var collection = new StudentCollection();
        collection.Add(new Student { Name = "John Doe", Age = 20 });
        collection.Add(new Student { Name = "Jane Smith", Age = 22 });
        collection.Add(new Student { Name = "Alex Johnson", Age = 21 });

        foreach (var student in collection) {
            Console.WriteLine($"Name: {student.Name}, Age: {student.Age}");
        }
    }
}
Example Output

Name: John Doe, Age: 20
Name: Jane Smith, Age: 22
Name: Alex Johnson, Age: 21
        

Benefits of Using `IEnumerable`

  • Improved Code Readability: Enables the use of `foreach` loops, making iteration cleaner and more understandable.
  • Deferred Execution: Iteration only happens when the `foreach` loop is executed, optimizing performance, especially with large collections.
  • LINQ Compatibility: `IEnumerable` is the foundation for LINQ, allowing you to perform powerful queries and manipulations on collections.
  • Flexibility with Custom Collections: Enables creating custom collection types that seamlessly integrate with standard C# iteration mechanisms.

Conclusion

The `IEnumerable` interface is a cornerstone of C#'s collection handling. By implementing it, you gain the benefits of standardized iteration, deferred execution, and seamless integration with LINQ, making your code cleaner, more efficient, and more maintainable.