IEnumerable Interface in C#

IEnumerable in C# is an interface that defines a standard way to iterate over a collection of objects. It provides a simple and efficient mechanism to access elements within a sequence, one at a time. It is used to define a collection that can be enumerated, meaning it can be iterated over using a foreach loop or other iteration constructs.

The IEnumerable<T> interface provides a single method, GetEnumerator(), which returns an enumerator that can be used to iterate through the collection.

public interface IEnumerable<out T> : IEnumerable
{
    IEnumerator<T> GetEnumerator();
}

Now let's see what is IEnumerator<T>.

public interface IEnumerator<out T> : IDisposable, IEnumerator
{
    T Current { get; }
}

It contains an abstract property named Current, which returns the element in the collection at the current position of the enumerator.

Here, you can see that IEnumerator<T> extends the IEnumerator interface. The nongeneric version of the IEnumerator interface contains two abstract methods.

public interface IEnumerator
{
    bool MoveNext();
    
    object Current { get; }
    
    void Reset();
}

Now, let's create a List<int> with some random values and assign it to an IEnumerable<int> reference variable.

IEnumerable<int> numbers = new List<int>{1,2,3,4,5};

The List<T> class implements IEnumerable<T>, enabling us to iterate over its elements using a foreach loop. This allows for polymorphic behavior, where a List<T> object can be assigned to an IEnumerable<T> reference variable.

Here, let me explain how a foreach loop works. Behind the scenes, the foreach loop code looks like this

var enumerator = numbers.GetEnumerator();

while (enumerator.MoveNext()) {
    Console.WriteLine(enumerator.Current);
}

var enumerator = numbers.GetEnumerator()

while (enumerator.MoveNext())

Console.WriteLine(enumerator.Current)

Output

IEnumerable Interface in C#

By understanding IEnumerable, you can effectively work with collections in C#, write more efficient and readable code, and take advantage of the powerful features of LINQ.

Happy Coding!!!