Wednesday 16 October 2013

Lambda Expression in C#

A lambda expression is an anonymous function and it is mostly used to create delegates in LINQ. Simply put, it's a method without a declaration, i.e., access modifier, return value declaration, and name.


Why do we need lambda expressions?

It's shorthand that allows you to write a method in the same place you are going to use it. Especially useful in places where a method is being used only once and the method definition are short. It saves you the effort of declaring and writing a separate method to the containing class.

Benefits:

  • Reduced typing. No need to specify the name of the function, its return type, and its access modifier.
  • When reading the code you don't need to look elsewhere for the method's definition.


Lambda Expression Syntax:


(Parameters)  =>  Expression (or) statement block
=> separates the parameters and statement body of the anonymous function

Type of Lambda Expression:

There are two type of Lambda expression. They are as follows

Statement Lambda
Statement lambda has a statement block on the right side of the lambda operator "=>"
For an Example:
              y => {return y * y }

Expression Lambda
Expression lambda has only an expression (no return statement or curly braces), on the right side of the lambda operator "=>"
For an Example:
            y => y * y

Features of Lambda Expression:

Lambda expressions themselves do not have type. In fact, there is no concept of a lambda expression in the CLR.
// ERROR: Operator '.' cannot be applied to
// operand of type 'lambda expression'
Type type = ((int x) => x).ToString();


A lambda expression cannot be assigned to an implicitly typed local variable since the lambda expressions do not have type.
// ERROR: Cannot assign lambda expression to an
// implicitly typed local variable
var thing = (x => x);

Jump statements (breaks, goto, continue) are not allowed within anonymous method/lambda expression. Similarly, you cannot jump into the lambda expression/ anonymous method from outside.

Variables defined within a lambda expression are accessible only within the scope of the lambda expression body.

Lambda expressions are used generally with the Func and Action delegates.
Func sqr = x => x * x;


Example Program that uses Lambda Expression:


using System;

class Program

{

    static void Main()

    {
      // Use implicitly typed lambda expression.
      // ... Assign it to a Func instance.
      //
      Func<int, int> func1 = x => x + 1;
      //
      // Use lambda expression with statement body.
      //
      Func<int, int> func2 = x => { return x + 1; };
      //
      // Use formal parameters with expression body.
      //
      Func<int, int> func3 = (int x) => x + 1;
      //
      // Use parameters with a statement body.
      //
      Func<int, int> func4 = (int x) => { return x + 1; };
      //
      // Use multiple parameters.
      //
      Func<int, int, int> func5 = (x, y) => x * y;
      //
      // Use no parameters in a lambda expression.
      //
      Action func6 = () => Console.WriteLine();
      //
      // Use delegate method expression.
      //
      Func<int, int> func7 = delegate(int x) { return x + 1; };
      //
      // Use delegate expression with no parameter list.
      //
      Func<int> func8 = delegate { return 1 + 1; };
      //
// Invoke each of the lambda expressions and delegates we created.
      // ... The methods above are executed.
      //
      Console.WriteLine(func1.Invoke(1));
      Console.WriteLine(func2.Invoke(1));
      Console.WriteLine(func3.Invoke(1));
      Console.WriteLine(func4.Invoke(1));
      Console.WriteLine(func5.Invoke(2, 2));
      func6.Invoke();
      Console.WriteLine(func7.Invoke(1));
      Console.WriteLine(func8.Invoke());
    }
}


Output

2

2

2

2
4

2
 2

In the example, we see the => syntax. This can be read as "goes to." It separates the arguments from the method body of a lambda expression. It is not a comparison operator. The => syntax separates the left from the right.


Left side: This is an empty parameter list, a formal parameter list, or an implicit parameter list from the body.



Right side: This can be a statement list inside curly brackets with a return statement, or an expression.


Func1 through func8 denote anonymous function instances. The Func<TResult> type is anonymous function with one result value and no parameter. The Func<T, TResult> type is a function with one parameter and one result value.


The delegate keyword is used to denote an anonymous function in the C# language. After the delegate keyword, you can use a formal parameter list or even omit the list if there are no parameters.


Finally, the program calls the methods that were all specified inside the method body. The Func generic type and the Action type have an instance method called Invoke. It receives a number of parameters that depends on the type.

Lambda Expression as an Event Handler:

Designer Page (aspx)

<form id="form1" runat="server"><div align="center"><h2>Anonymous Method Example</h2><br /><asp:Label ID="lblmsg" runat="server" ForeColor="Green" Font-Bold="true"></asp:Label><br /><br /><asp:Button ID="btnReset" runat="server" Text="Reset" />  <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" /></div>
</form>












Code behind (C#)

protected void Page_Load(object sender, EventArgs e)
{
// Click Event handler using Regular method
btnReset.Click += ClickEvent;
// Click Event handler using Anonymous method
btnSubmit.Click += delegate { lblmsg.Text="Submit Button clicked using Anonymous method"; };
// Click Event handler using Lamda expression
btnCancel.Click += (senderobj, eventobj) => { lblmsg.Text = "Cancel Button clicked using Lamda expression"; };
}
protected void ClickEvent(object sender, EventArgs e)
{
    lblmsg.Text="Reset Button clicked using Regular method";
}

Output










About Author:
Anand Sahayaraj is technology lover and is important part of Systems Plus technology Think Tank. He works in Systems Plus Pvt. Ltd. and actively contributes to technology. He can be contacted at: anand.s@spluspl.com

No comments:

Post a Comment