Delegate to Lambda - Part 4
Delegate to Lambda - Part 4

This is the 4th and last part of the "Delegate to Lambda" series. So far we have seen some of the important features of "delegate" in c#, such as, creating new delegate instances by passing matched method name, assigning method to a delegate instance directly instead of creating new delegate instances and delegate chaining. The 4th part of this series is about anonymous method that came in c# 2.0, which is not so much used now a days but it's very important to know about it because anonymous method is closely related to lambda expressions. In this topic we will also see how we can turn an anonymous method to a labmda expression.


What is an anonymous method?

An anonymous method is a method that does not have a name. Simple haahh! But how do we write and call a method that does not even have a name? Well, let's explore it by example.
Earlier we have seen code like this:

private delegate bool Mydelegate(int yourNumber);//Declaration of delegate
 
        static void Main(string[] args)
        {
            var del1 = new Mydelegate(GreaterThanFive);//Passing matched method
            var result1 = del1(10);//invoking delegate
            Console.WriteLine(result1);   
            Console.ReadKey();
        }
        private static bool GreaterThanFive(int yourNumber)//Matched method
        {
            return yourNumber > 5;
        }

Here, at first we have declared a delegate that takes an int and returns a bool. Then we created method called "GreaterThanFive" that has same signature like the delegate (note: unlike method signature, delegate signature includes parameters and return type). Finally we have invoked the delegate by passing some int value. Plain and simple.

But, instead of writing the method that's gonna run when we invoke the delegate, we can write the whole method inside the delegate while constructing it.

static void Main(string[] args)
        {
           var del2 = new Mydelegate(
                delegate (int number)
                    {
                        return number > 5;
                    }
            );
            var result2 = del2(20);
            Console.WriteLine(result2);
            Console.ReadKey();
        }

Notice, we have copied the whole method called "GreaterThanFive" that we created earlier but this time we did not mention the name. Instead we put the keyword "delegate". It c# way of saying that, hei, when I invoke any instance of "MyDelegate" please run this bunch of code. This is exact same way of pointing to a method that would run the same bunch of code.

So, in short we are running a method body but this time the method does not have a name. And, this allows us to completely discard the "GreaterThanFive" method.

Heading towards Lambda

Anonymous method opened the door for lambda expression in c# 3.5. The following key points allowed us to write the same code in much simpler way.

Well, at this level compiler knows that "MyDelegate" is a delegate instance and we have to pass a method that has the same signature to it. As a result we don't need the delegate keyword or the method name.

var del3 = new Mydelegate( (int number) { return number > 5; });

Here, the part inside parenthesis "(int number)" denotes the method parameters and the part inside curly braces "{return number > 5; }" denotes the body of the method.
To indicate both part of the method separately, c# guys came up with the "=>" operator. So, now it looks like the following

var del3 = new Mydelegate( (int number) => { return number > 5; });

At this point, we know that MyDelegate takes an int value as parameter. So, we can get rid of the parameter type. Compiler can figure it out for us.

var del3 = new Mydelegate( (number) => { return number > 5; });

Then, since we know that MyDelegate returns something (bool in this case) we can get rid of the return keyword also.

var del3 = new Mydelegate( (number) => { number > 5; });

Since, we have only one parameter, we can delete the "()" surrounding the parameter.

var del3 = new Mydelegate( number => { number > 5; });

But, if we would have more than one parameter then, we had to use the "()" surrounding the parameters.

Finally, as there is only one line of code in the method body "inside {}", we can also delete the "{}". Then it looks like

var del3 = new Mydelegate( number =>  number > 5 );

We have discarded all the stuff the we could figure out automatically. The last bit is just a matter of beautifying the look of the expression. Instead of saying "number" we could just say "n". Because, it’s easy to write and nice to look. So, it becomes,

var del3 = new Mydelegate( n => n > 5 );

Then we can just invoke the delegate and capture the return value if we want like the following

var result = del3(20);
Console.WriteLine(result3);//prints true

In this series, I have tried my best to explain delegate in the simplest way I could. One thing to bear in mind that, delegate is one of the most important and quite advance topic. It might take a while to fully understand the whole mechanism. So, keep on practicing and learning. 

October 14, 2014
Jahan Sarwar