简体   繁体   中英

Why `using System.Linq` adds functionality to other libraries

I've been using C# for some years now but I've been a little too lazy to learn about all the new features of it as they are introduced. Perhaps one of major features would be Linq , which I never understood its benefits. But never mind that, what I'm interested in right now is a black magic that happens when the using System.Linq statement is added to a file.

Recently I've been using MongoDB in C# and I wanted to retrieve a single document out of database. Here's how it is done:

var cursor = colletion.FindAs<Entity>(query).SetLimit(1);
var en = cursor.Single<Entity>();

The above code extracts one single document of type Entity out of a collection. The part that amazes me is that the Single method of cursor is recognized only when the using System.Linq is added to the file. How is that possible?

That's because Single is an extension method .

Extension methods are static methods within static classes and their first input parameter are marked with the this keyword. Example:

namespace System.Linq 
{
    public static class Enumerable
    {
        public static IEnumerable<T> Single<T>(this IEnumerable<T> source)
        {
            ...
        }
    }
}

When the compiler sees a.Single() where a is an IEnumerable<T> and cannot find such a method on that object, it will search for an extension method that takes an IEnumerable<T> in its first parameter.

In order for this resolution to work, the static class that exposes the extension method Enumerable needs to be within scope , which you bring in scope by importing the System.Linq namespace.

From msdn extension methods

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

The most common extension methods are the LINQ standard query operators that add query functionality to the existing System.Collections.IEnumerable and System.Collections.Generic.IEnumerable types. To use the standard query operators, first bring them into scope with a using System.Linq directive. Then any type that implements IEnumerable appears to have instance methods such as GroupBy, OrderBy, Average, and so on. You can see these additional methods in IntelliSense statement completion when you type "dot" after an instance of an IEnumerable type such as List or Array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM