What's the usage of AsEnumerable

  • .NET

The extension method AsEnumerable is coded as follows:

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

You can wonder what is the interest of such a method. To answer this question you must understand how extensions methods work.

What is an extension method? An extension method extends the functionality of a class from the outside (ie. without modifying it nor extending it). Thus, these methods are necessarily public and only access the public visibility of the object they extend. To be clear, this is just a syntaxic sugar. Without extension methods, you must call the static method as usual:

Enumerable.AsEnumerable(obj);

With extension methods, you can write:

obj.AsEnumerable();

The Enumerable does not appear in the second syntax. AsEnumerable must therefore be determined by the compiler. How to do it?

  • Several extension methods can extend the same type.
  • Several extension methods can extend types belonging to the same class hierarchy

First conclusion, there may be conflicts! Indeed, the extensions methods are searched by the compiler in the current scope. This means the right extension method is found at compile time, and not at run time.

  • If several extension methods are found for the same type then a compilation error is raised.
  • If several extension methods are found for different types in the same hierarchy (classes or interfaces) then the one that match the type of the variable takes precedente over others.

Almost all the features of Linq (where, orderby, select, count, etc.) take as parameter IEnumerable<T> or IQueryable<T>. The method AsEnumerable, by simply returning an IEnumerable<T> from any object implementing this interface, makes it possible to force the call of methods of extension of IEnumerable<T> instead of IQueryable<T>.

Follow me:
Enjoy this blog?Buy Me A CoffeeDonate with PayPal

Leave a reply