C# IEnumerable

Loop

The IEnumerable interface appears throughout C# programs. It specifies that the underlying type implements the GetEnumerator method. It enables the foreach-loop to be used. It often interacts with methods from the System.Linq namespace.

Foreach

Example

Generic type

An IEnumerable generic interface is returned from query expressions. A query expression that selects ints will be of type IEnumerable<int>. On an IEnumerable variable, you can also use the foreach-loop.

Tip:You can apply lots of transformations to an IEnumerable instance, including the ToList and ToArray conversions.

ToListToArrayAverage
Program that uses IEnumerable: C#

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

class Program
{
    static void Main()
    {
	IEnumerable<int> result = from value in Enumerable.Range(0, 2)
				  select value;

	// Loop.
	foreach (int value in result)
	{
	    Console.WriteLine(value);
	}

	// We can use extension methods on IEnumerable<int>
	double average = result.Average();

	// Extension methods can convert IEnumerable<int>
	List<int> list = result.ToList();
	int[] array = result.ToArray();
    }
}

Output

0
1

Example 2

Programming tip

Because many types implement IEnumerable, you can pass them directly to methods that receive IEnumerable arguments. The type parameter must be the same. The next method receives an IEnumerable argument. You can pass Lists or arrays to it.

ListArray
Program that uses IEnumerable argument: C#

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	Display(new List<bool> { true, false, true });
    }

    static void Display(IEnumerable<bool> argument)
    {
	foreach (bool value in argument)
	    Console.WriteLine(value);
    }
}

Output

True
False
True

Also, you can implement IEnumerable on a type to provide support for the foreach-loop. This is done through the GetEnumerator method. This is currently outside the scope of this article.

Summary

The IEnumerable<T> interface is a generic interface that provides an abstraction for looping over elements. In addition to providing foreach support, it allows you to use extension methods in the System.Linq namespace.

Extension Method

C#: Interface