Blogger news

Blogger templates

Friday, February 4, 2011

Delegate, Anonymous Method, Lambda Expression

Lamda Expression
Lamda expression is C# 3.0 language feautures and it’s nothing but just higher version of anonymous method. Anonymous is nothing but higher version of delegate. So before dig into lamda expression I will give you basic understanding of delegate and anonymous methods.

Delegate
Simply we can say delegate is nothing but a function pointer, means a delegate can point to any method which satisfy the delegate’s signature. For example the meaning of this delegate is,public delegate string MyDelegate(int myParam);

Using 
MyDelegate I can point to any method which accepts a parameter of int and return string. For example I can point the method,
public static string HelloWorld(int hello)
        {
            return "Hello World!!";
        }
with
MyDelegate. But I can’t point the method,

public static string Wrong()
        {
            return "I can’t point this method with MyDelegate because it is not accepting an integer parameter!!";
        }
with
MyDelegate because it will not match with MyDelegate’s signature.

I can point “HelloWorld” with MyDelegate as,




        static void Main(string[] args)
        {
            MyDelegate del = HelloWorld;
     Console.WriteLine(del(100));
            Console.ReadKey();

        }

The output would be Hello World!!". After pointing the method “HelloWorld” with MyDelegate then when ever we call “del” it will run “HelloWorld” method. The entire program look’s like,

using System;

namespace ConsoleApplication4
{
    class Program
    {
        public delegate string MyDelegate(int myParam);
        static void Main(string[] args)
        {
            MyDelegate del = HelloWorld; Console.WriteLine(del(100));
            Console.ReadKey();
        }
        public static string HelloWorld(int hello)
        {
            return "Hello World!!";
        }
    }
}

This is all about the very basics of delegate.

Anonymous Methods
Anonymous method was introduced in C# 2.0. Before the anonymous method we need a physical method which matches the delegate’s signature to point with delegate as I discussed in the previous chapters. In anonymous method we don’t need a method to point the delegate. Here I am rewriting the “MyDelegate” which now point with anonymous method.

public delegate string MyDelegate(int myParam);
        static void Main(string[] args)
        {
            MyDelegate del = delegate(int hello) { return "Hello World!!"; };
            Console.WriteLine(del(100));
            Console.ReadKey();
        }

The output would be “Hello World!!"”. Now we can operate the sample,

MyDelegate del = delegate(int hello) { return "Hello World!!"; };

Here “int hello” is the method parameter and whatever inside curly brace is method body. Say if I have a delegate which accepts two input parameters of type “int” and “string” and return “string” so we can write it as,

TestDelegate test= delegate(int a,string b) { return "Method accepts two parameters!!" };

In anonymous method we don’t need a physical method. We can point method to delegate like
Delegate(Method parameters){ method body};
This all about simple basics of anonymous methods.


Lambda Expression
Now  I am going to introduce the real beauty, Lambda Expression. Lambda expression is nothing but one step above anonymous method. It’s C# 3.0 language feature. Again I am take the same example of delegate which point to a method which takes one input parameter of type  “int” and returns a “string” type. We can implement it using  lambda expression as,

MyDelegate del = a => "Hello World!!";
Console.WriteLine(del(100));

Hats off to the new language feature, the output is again Hello World!!". The entire program looks like,


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication5
{
    class Program
    {
        public delegate string MyDelegate(int myParam);
        static void Main(string[] args)
        {
            MyDelegate del = a => "Hello World!!";
            Console.WriteLine(del(100));
            Console.ReadKey();
        }
    }
}

In the upcoming session I will got in depth and every aspects of lambda expression using many examples.


Now we can operate lambda parts by parts. See the image below,

See the line  MyDelegate del = a => "Hello World!!";
Lambda has two parts, a left part and right part. Left part is input parameter.  So here “a” is input parameter means if we write a method to  point the delegate “del” it should looks like,
public static string HelloWorld(int a)
        {
            return "Hello World!!";
        }
Here also “a” is input parameter of type “int”. In lambda expression compiler can understand “a” is the input parameter of type “ int” or we can explicitly write the type of input parameter as,
MyDelegate del = (int a) => "Hello World!!";

But compiler is powerful to know the type explicitly. Compiler can understand it by checking the signature of the delegate.
Now we can check the right side of lambda. Right hand side is nothing but the return value from the method. In our example the lambda expression returns "Hello World!!", exactly as the “HelloWorld” method. Lamda expression can understand the return type by checking the delegate signature.
Say  I want to write lambda expression for a delegate which accepts two input parameters of type “int” and return the sum of that two input parameters. How it should looks like? Before explain that I can again write a method for the same scenario,
public static int GetSum(int param1,int param2)
        {
            return param1 + param2;
        }
Now I am converting this to lambda expression. I want two input parameters so I can write it as (param1, param2) and I want to return the sum, so I can write it as param1+param2. Now we can combine this together as ,
(param1, param2)=> param1+param2;
When we point this to delegate it should looks like,
SumDelegate sum = (param1, param2) => param1 + param2;
Console.WriteLine(sum(100, 150));

Yes the output would be 250.

These types of lambda’s are called expression lambda. If we write a statement in lambda then it is called statement lambda. We will go to statement lambda’s in the upcoming session.

No comments:

Post a Comment