Home
C#
AsEnumerable Method
Updated Sep 26, 2022
Dot Net Perls
AsEnumerable. The IEnumerable interface defines a template that types can implement for looping. AsEnumerable is a generic method that converts its argument to IEnumerable.
IEnumerable
Casting info. AsEnumerable allows you to cast a specific type to its IEnumerable equivalent. So this is a method that performs a cast on its argument and returns it.
Example. We must include the System.Linq namespace to access AsEnumerable. When you have an IEnumerable collection, you typically access it through queries or a foreach-loop.
int Array
Extension
Next The example code also shows the implementation of AsEnumerable in the .NET Framework. This only casts the parameter and returns it.
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);
        }
    }
}
5 6
public static IEnumerable<TSource> AsEnumerable<TSource>( this IEnumerable<TSource> source) { return source; }
Output notes. You can see that the value returned by the AsEnumerable method invocation is typed with the implicit type var. This makes the syntax clearer.
var
Info You could explicitly specify the type as IEnumerable int instead. This would be harder to read.
A summary. IEnumerable provides a contract that allows a typed collection to be looped over. To get an IEnumerable from a List or array, you can invoke the AsEnumerable extension method.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 26, 2022 (edit).
Home
Changes
© 2007-2025 Sam Allen