1. Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.

Sample Code C# : Lambda Expressions

Discussion in 'Programming & Webmastering' started by Kreij, Mar 19, 2008.

  1. Kreij

    Kreij Senior Monkey Moderator Staff Member

    Joined:
    Feb 6, 2007
    Messages:
    13,881 (4.87/day)
    Thanks Received:
    5,616
    Location:
    Cheeseland (Wisconsin, USA)
    Sample Code C# 3.0: Lambda Expressions

    Well, I figured it was time for old Uncle Kreij to drop another programming tip on you guys. This because I hit a programming wall using the Express editions for my project, and talked the boss into letting me purchase a full copy of Visual Studio 2008 Pro. :rockout:
    So while I am waiting for it to arrive, I have a little time on my hands.

    What the heck is a Lambda Expression?

    A Lambda expression (LE) is an anonomous function that can contain expressions and statements that can be used to create delegates or expression tree types.

    I can hear it already, "Thanks Kreij" :wtf: :nutkick:

    Let me show you a very simple example.

    Let's say you have a form with a button (button1) and a text box (textbox1). When you click the button, you want to write the current date into the textbox. You do this by creating an event handler for the button1's "Click" event.

    The code would normally look like this...
    Code:
    button1.Click += [color=blue]new[/color] EventHandler(button1_Click);
    
    [color=blue]void[/color] button1_Click ([color=blue]object[/color] sender, [color=teal]EventArgs[/color] e)
    {
        textbox1.Text = [color=teal]DateTime[/color].Now.ToShortDateString();
    }
    
    All LE's us the lambda operator ( => ) which means "goes to". The left side of the operator takes input parameters (if any) and the right side gets the expression or statement block.

    So the new event handler would look like...
    Code:
    button1.Click += (s, e) => 
        { textbox1.Text = [color=teal]DateTime[/color].Now.TosShortDateString(); } ;
    
    The cool thing is that the input parameters in the case (Object & EventArg) are inferred by the compiler and do not have to be listed explicitly in the input parameters. You can add any number of statements within the code block "{ }"

    You can use them anywhere a delegate is expected, meaning, anywhere any anonomous method can be used.

    Maybe someone will find this useful, maybe not.
    If anyone would like to see more examples of this, just post.

    Have fun coding!

    Edit : Sorry I forgot to mention that lambda expressions are a new feature in 3.0
     
    Last edited: Mar 22, 2008

Currently Active Users Viewing This Thread: 1 (0 members and 1 guest)

Share This Page