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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.