Sunday, January 29, 2012

C# 3.0 for Beginners - Extension Methods - Part 1

All C# code is eventually executed by the .NET CLR. This requires the C# compiler to transform the LINQ query expressions to a format that is understandable by .NET. LINQ query expressions are transformed into method calls, which are called extension methods. These methods are slightly different from normal methods. Lets discuss them in more detail:

Consider the example that we saw in my previous posts.
    public static void GetIExplorer()
    {
        //  1. Data Source
        Process[] processes = Process.GetProcesses();

        //  2. Query Creation
        IEnumerable<int> query =
              from p in processes
              where p.ProcessName.ToLower().Equals("iexplore")
              select p.Id;

        //  3. Query execution
        foreach (int pid in query)
        {
            Console.WriteLine("Process Id : "+pid);
        }
    }

The query creation in part two transforms in a series of method calls on the data source 'processes' as follows.
    IEnumerable<int> query =
            processes.Where(p => p.ProcessName.ToLower().Equals("iexplore"))
                     .Select(p => p.Id);

The Select clause, however, it not essential. It may be ignored and you might retrieve a list of processes and not their process Ids. The Select clause here specifies the entity to be selected in detail, in the above example, it was the process id belonging to the selected process.

Now, you might wonder that since the Where() method was called on the 'processes' Array, the Array object might have implemented the Where() method. But, that's not quite the case here. The method Where() is called an extension method and is used for extending a type's functionality.

We have also made use of lambda expressions here. We will discuss their significance later in detail, but, for now, you can look at it as if it were a provision to select entities based in certain specified conditions. In the above code the variable 'p' indicates each element in the 'processes' array which is subjected to an expression evaluation (p.ProcessName.ToLower().Equals("iexplore")), and only if the result of the condition evaluation is true, will the item be selected as the result of the query. These are filtering expressions.

In my next post I will describe how to define and use your own extension methods.

No comments:

Post a Comment