Blue Theme Orange Theme Green Theme Red Theme
 
Click Here for 3 Month Free of ASP.NET Hosting!
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
World Class ASP.NET Hosting - 3 Month Free Hosting, Click Here!
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » C# Language » Lambda Expression in c# 3.0

Lambda Expression in c# 3.0

This article will explain about Lambda expression and its usage. This article will also give differences between Lambda expression and Anonymous method. This article will talk about type inference in Lambda expression. This will also talk about delegate type conversion of lambda expression.

Author Rank:
Technologies: General Programming,Visual C# .NET
Total downloads : 22
Total page views :  2495
Rating :
 2/5
This article has been rated :  1 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
DelegateTesting.zip
 
Powerful ASP.NET Hosting w/ NO Setup Fees. Click Here!
Become a Sponsor


Related EbooksTop Videos


This article will explain about Lambda expression and its usage. This article will also give differences between Lambda expression and Anonymous method. This article will talk about type inference in Lambda expression. This will also talk about delegate type conversion of lambda expression.

We will start with a code. This is a very simple code which is printing Hello World. But this is done with help of Lambda Expression.

image1.gif

  1. Lambda Expression provides a concise functional syntax for writing anonymous method.
  2. It is a type safe way to write functions that can be passed as argument for subsequent evaluation.
  3. Lambda expression are superset of anonymous method.
  4. It can contain either and statement or an expression.
  5. It may have or may not have parameters.
  6. Its parameter could be implicitly or explicitly type.

    image2.gif
  7. It uses the lambda operator. => This operator is known as GOES TO 

    image3.gif
     
  8. Different lambda expressions are

    image4.gif
     
  9. There are two types of Lambda expression

    image5.gif

    Expression Lambda

    A lambda expression, which is having expression at right hand side is called Expression lambda.

    image6.gif

    Examples:

    image7.gif

    Statement Lambda

    A lambda expression, which is having statement at right hand side is called Statement lambda.

    image8.gif

    Examples:

    image9.gif

Parameter types in Lambda Expression

image10.gif

  1. For explicit type parameter, each parameter does have their type.

    image11.gif
     
  2. For implicit type parameter, type of parameter is inferred from compatible delegate type.

    image12.gif

Working Example

See, the below code. How lambda expression is being used to find out name of the authors having more than 100 articles.

image13.gif

Output

image14.gif

Lambda Expression conversion to Compatible delegate type
Lambda expression is considered as a value, which is having special conversion rules. The Lambda expression value does not have a type but can be converted to compatible delegate type.

Let us suppose,

D-> Delegate

L-> Lambda Expression

Then D and L are called compatible if

  1. D and L have same number of parameters.
  2. If L has explicit type parameter then L should also have same type parameter list.
  3. If L has implicit type parameter then L should not have Ref and Out parameters.
  4. If D has a void return type and L is an expression type lambda expression then body of L is a valid expression and considered as a statement expression.
  5. If D has a void return type and L is a statement type lambda expression then body of L is a valid statement block where no expression contains return statement.
  6. If D is returning some type and L is an expression type lambda expression then body of L is a valid expression, if that is implicitly convertible to the return type of D.
  7. If D is returning some type and L is a statement lambda expression then body of L is a valid statement body if in which each Return statement specifies the type which could be implicitly convertible to the return type of D.

Example
Let us suppose, there is a delegate

delegate void MyDelegate(int num);

Below lambda expression would work fine due to rule 5 stated above.


MyDelegate r = (num) => Console.WriteLine(num) ;

Below lambda expression would not work fine due to failure of rule 5 stated above.

image15.gif

Lambda Expression and Anonymous method

  1. Lambda Expression permits parameter type to be omitted and inferred whereas anonymous method requires parameter type to be explicitly stated.
  2. The body of lambda expression can be expression or statement whereas body of anonymous method only could be statement.
  3. Lambda Expression within an expression body can be converted to expression tree.

Type inference in Lambda Expression

Let, we suppose we are assigning a value to a variable like below. Compiler will report an error "Cannot assign lambda expression to an implicitly typed local variable". Because c# type inference cannot be used to infer to infer type of a lambda expression.

image16.gif

This could be solved by, explicitly declaring the type of the lambda expression.

Func<int> res = () => 9;

For inferred return type of a lambda expression L is determined as follows:

  • If L is an expression type Lambda Expression, the type of that expression is the inferred return type of L.
  • If L is a statement type Lambda Expression, if the set formed by the types of the expressions in the block's return statements contains exactly one type to which each type in the set is implicitly convertible, and if that type is not the null type, then that type is the inferred return type of L.
  • Otherwise, a return type cannot be inferred for L.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Dhananjay Kumar
I am Dhananjay Kumar. I passed computer science  & engineering from AEC Agra in year 2007. I born and brought up in Jamshedpur , Jharkhand.I am MCTS on WCF, MOSS Development , .Net Framework 2.0 Web Application so far. I read and write on WCF, SilverLight , SharePoint , ASP.Net MVC, ASP.Net 3.5 Extensions , .Net 4.0 , C# 3.0 , C# 4.0 etc etc. Currently , I am working for UST Global as Software Engineer and active member of Microsoft COE team .
 
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.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
DelegateTesting.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
expression tree by joanne On October 18, 2009
i would like to ask some sample codes of an expression tree using c#...
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved