Blue Theme Orange Theme Green Theme Red Theme
 
DevExpress Free UI Controls
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » C# Language » Delegate to Lambda Expression

Delegate to Lambda Expression

This article will not give any theoretical definition of Delegate, Anonymous method and Lambda Expression.

Author Rank :
Page Views : 2521
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Objective 

This article will not give any theoretical definition of 
  1. Delegate  Read theory of Delegate here
  2. Anonymous method
  3. Lambda Expression  Read theory of Lambda expression here 
I am going to give a story type discussion from Delegate to Lambda expression. 

1.gif
 
Let us say, there is a requirement that you need to pass one function as parameter of another function.   This can be easily done through function pointer in language like C++ but in C#, we cannot pass a function. 

There are two functions 

int Add(int number1, int number2)
{
    return number1 + number2;
}

int Sub(int number1, int number2)
{
    return number1 - number2;
}

Now we need to pass the above function in other function called Display. 

2.gif 

Sometime we need to pass add function or sometime we need to pass Sub function to display the result of the add or sub. 

So here in our requirement we will have to pass something, which can represent both Add and Sub function. 

If we notice, signature of both Add and Sub function is exactly the same. Both are returning an Integer parameter and taking as input two integer parameters. 

So if we can have something which can represent Add and Sub function then we can pass that representation as parameter. 

So here delegate comes into picture. We will pass delegate of Add and Sub function as parameter of Display function. 

Now signature of Display function can be modified as 

3.gif
 
So now we have the task to create the delegate.  We can say delegate is representation of function.  While creating a delegate only one thing we need to keep in minds that, "Delegate can refer only those functions which are having exactly the same signature as of delegate"

So for our purpose we will have to declare a delegate with return type integer and taking two integer parameters. 

4.gif
 
In above delegate declaration 
  1. Integer is return type. 
  2. Name of the delegate is DelegateCal 
  3. There are two integer input parameter. 
So, DelegateCal only can refer functions which are having integer return type and two integer parameters. 

So now we can assign a function to delegate as below, 

5.gif
 
Here signature of Add and DelegateCal is same.  Not a point here is that, you can assign function with different signature to delegate else you will be get a compile time error. 

So, now Display function can be modified as 

6.gif
 
Now we are meeting our requirement and we can pass any function with the signature matching of the delegate to the display function. 

Program.cs 

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

namespace ConsoleApplication18
{
    class Program
    {
        delegate int DelegateCal(int a , int b);
        static void Main(string[] args)
        {
            DelegateCal d = Add;           
            display(d);
            Console.Read();
            d = Sub;
            display(d);
            Console.ReadKey(true);
        }
        static  void display(DelegateCal d)
        {
          int result = d(7,2);
          Console.WriteLine(result);
        }
        static int Add(int number1, int number2)
        {
            return number1 + number2;
        }
        static int Sub(int number1, int number2)
        {
            return number1 - number2;
        }    
    }
}

Explanation 
  1. We have declared a delegate with signature, return type integer and two integer input parameters. 
  2. Created two functions Add and Sub. Both are taking two integer parameters and returning an integer. 
  3. Created a Display function which is taking delegate as parameter. 
  4. Assigning the function to the delegate. 
  5. Calling the display function. 
Output 

7.gif 

Anonymous method 

Now let us say you need to create a function for multiply.  Now we have an option that we can create a function for multiply [with signature same as delegate] 

8.gif 

But, what if we don't want to create a function rather we want the function at the run time or on the fly without any name.  We can very much achieve that using anonymous method. 

9.gif
 
In above code, 
  1. d is the delegate. 
  2. delegate keyword is being used to create an anonymous method. 
  3. Anonymous method does not have any name 
  4. There are two input parameters for anonymous method.
  5. d now can be passed as parameter to display function. 
So from above code we can conclude that we have created a function without name (anonymous method) and assigned that to a delegate with the same signature. 

So now rather than creating a function explicitly using anonymous method we are creating that on the fly or at the run time. 

Program.cs 

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

namespace ConsoleApplication18
{
    class Program
    {
        delegate int DelegateCal(int a , int b);
        static void Main(string[] args)
        {
            DelegateCal d = Add;           
            display(d);
            Console.Read();
            d = Sub;
            display(d);
            Console.ReadKey(true);
            d = delegate(int num1, int num2)
            {
                return num1 * num2;
            };
            display(d);
            Console.ReadKey(true);
        }
        static  void display(DelegateCal d)
        {
            int result = d(7,2);
            Console.WriteLine(result);
        }
        static int Add(int number1, int number2)
        {
            return number1 + number2;
        }
        static int Sub(int number1, int number2)
        {
            return number1 - number2;
        }
    }
}

Output 

10.gif 

Lambda expression 

If we see the anonymous method 
  1. We are using the keyword delegate. 
  2. We are explicitly giving the data type of input variables.
  3. Readability is not very high. 
Lambda expression allows us to write anonymous function in very concise way.  Readability is high. 

Lambda expression uses goes to operator. 

So, if we modify the above anonymous method as below, 

11.gif
 
In above code we are directly in lining the code for division, rather than creating any function or anonymous method. 

Program.cs

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

namespace ConsoleApplication18
{
    class Program
    {
        delegate int DelegateCal(int a , int b);
        static void Main(string[] args)
        {
            DelegateCal d = Add;           
            display(d);
            Console.Read();
            d = Sub;
            display(d);
            Console.ReadKey(true);
            d = delegate(int num1, int num2)
            {
                return num1 * num2;
            };
            display(d);
            Console.ReadKey(true);         
            display((num1, num2) => { return num1 % num2; });
            Console.ReadKey(true);
        }
        static  void display(DelegateCal d)
        {
            int result = d(7,2);
            Console.WriteLine(result);
        }
        static int Add(int number1, int number2)
        {
            return number1 + number2;
        }
        static int Sub(int number1, int number2)
        {
            return number1 - number2;
        }
    }
}

Output 

12.gif

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Dhananjay Kumar
Dhananjay Kumar is a developer who blogs at http://debugmode.net/. He is Microsoft MVP ,Telerik MVP and Mindcracker MVP. You can follow him on twitter  @debug_mode
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.