TheDeveloperBlog.com


C# AsEnumerable Method

AsEnumerable. The IEnumerable interface is a generic interface. This means it defines a template that types can implement for looping. The AsEnumerable method is a generic method. It allows you to cast a specific type to its IEnumerable equivalent.


Example. We use AsEnumerable on an int array. AsEnumerable is an extension method and you must include the System.Linq namespace to access it. When you have an IEnumerable collection, you typically access it through queries or a foreach-loop.

Int ArrayExtension Method

Next: The example code also shows the implementation of AsEnumerable in the .NET Framework. This only casts the parameter and returns it.

C# program that uses AsEnumerable method

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	// Create an array type.
	int[] array = new int[2];
	array[0] = 5;
	array[1] = 6;
	// Call AsEnumerable method.
	var query = array.AsEnumerable();
	foreach (var element in query)
	{
	    Console.WriteLine(element);
	}
    }
}

Output

5
6

Implementation of AsEnumerable: .NET

public static IEnumerable<TSource> AsEnumerable<TSource>(this IEnumerable<TSource> source)
{
    return source;
}

You can see that the value returned by the AsEnumerable method invocation is typed with the implicit type var. This makes the syntax clearer. You could explicitly specify the type as IEnumerable<int> instead.

Var

Summary. The IEnumerable interface in the C# language provides a contract that allows a typed collection to be looped over. More specific, physical collections such as arrays or Lists can be used as IEnumerable collections.

And: To acquire a reference from one of those types to a simple IEnumerable type, you can invoke the AsEnumerable extension method.