The evolution of Delegate, Anonymous Method, Lambda Expression
Here's I am going to write something about the evolution of Delegate, Anonymous Method, till Lambda Expression. Here's I will use a build in delegate, Predicate<T> to give the example. My example is simple. There's a collection of integer (I call it intList). I fill it up with numbers (1, 2, 3, 4, and 5). My goal is to find out odd numbers in the collection. It's very simple.
List<int> intList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8 };
Traditionally, what we're going to do is to enumerate all members in the intList collection using for or foreach. If the member meets the criteria, we'll save it to our result.
List<int> oddResult = new List<int>();
foreach (int item in oddResult)
{
if (item % 2 != 0)
oddList.Add(item);
}
We'll have the result in oddResult. That's imperative way to find our result. We tell the computer What To Do to achieve our goal. (We tell it to enumerate the collection).
But this isn't what I am going to show. I'm going to show you another paradigm to do it.
First I will use Delegate. In C# 1.0, Microsoft introduced a special type which is called Delegate. Delegate type has a capability to hold address of method.
public static bool IsOdd(int x)
{
return x % 2 != 0;
}
Predicate<int> criteria = new Predicate<int>(IsOdd);
List<int> oddResult = intList.FindAll(criteria);
First, I created a method IsOdd, and then define the rule in it. Next, I will use Predicate delegate as my criteria to search something in intList using FindAll method. (A comprehensive explanation about Predicate<T> can be found at here by Mr Norman). In short, I am going to tell the computer, "Please find me members that meet the criteria". We tell the computer, what we want. I didn't tell it how to find, just told it what I want to find.
In C# 2.0, there's another enhancement in language capability called "Anonymous Method". Yup!!! It's a method without name. It is slipped in our method. It simplifies our code like this:
Predicate<int> criteria = delegate(int x)
{
return x % 2 != 0;
};
List<int> oddResult = intList.FindAll(criteria);
Or even you could simplify it become:
List<int> oddResult = intList.FindAll(delegate(int x)
{
return x % 2 != 0;
});
That's what we call "Anonymous Method".
Now, in C# 3.0, you could write it like this:
List<int> oddResult = intList.FindAll(x => x % 2 != 0);
There's a lambda operator ( => ), which read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side hold the expression or statement block.