Extension Methods

As discussed in Chapter 10, “Methods,” in the section “Extension Methods,” extension methods piggyback on the using directive to be brought into scope. This is quite special in the language because it makes the resolution of members depend on namespaces, where the using directive only influenced types in the pre-C# 3.0 era. A good example of the use of extension methods is found in LINQ:

using System.Linq;class Program{    static void Main()    {        var rabbits = new[] { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 };        var evenRes = rabbits.Where(x => x % 2 == 0);        ...    }}

Again, the use of using directives is a compile-time thing only because the above is turned into a static Where method ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.