Anonymous Method, Lambda Expression

Anonymous Method – a method without name (available from .Net Framework 2.0)
You don’t declare anonymous methods like regular methods. Instead they get hooked up directly to events.  To create an Anonymous method, use delegate keyword with or without parameter followed by code block
Example 1: Anonymous method in event handling
public Class1()
        Button btnHello = new Button();
        btnHello.Text = “Hello”;
        btnHello.Click +=
                btnGoodBye.Click +=
                  delegate(object sender, EventArgs e)
                    string message = (sender as Button).Text;
Example 2: Anonymous method in parameter
void StartThread()
        System.Threading.Thread t1 = new System.Threading.Thread
                            System.Console.Write(“Hello, “);
Example 3
Normal method
bool IsGreaterThan20(int n)
    return n>20;
int GetNumbersGreaterThan20(List<int> numbers)
    return numbers.FindAll(IsGreaterThan20);
Same code using the Anonymous method
int GetNumbersGreaterThan20(List<int> numbers)
    return numbers.FindAll(delegate(int n)
    return n>20;
1.   Don’t declare a return type
2.   The keyword delegate is used instead of a method name
3.   Declare the method’s arguments to match the signature of the delegate
4.   Don’t declare variables whose names conflict with variables in the outer method

Lambda Expression – It builds on Anonymous method concept
Syntax: argument-list => expression
We can replace the anonymous method which is shown in example 3 with the following code:
int GetNumbersGreaterThan20(List<int> numbers)
    return numbers.FindAll ( n=> n>20);
Another examples:
1.   delegate int Delegate1(int i);
static void Main(string[] args)
    Delegate1 DelegateObj = x => x * x;
    int j = DelegateObj (5); //j = 25
2.   slider.ValueChanged+= (sender, e)=> label.Text=slider.Value.ToString();
Some useful lambda expressions:
//find the first number in the list that is below 10
List<int> numbers=GetNumbers();
int match=numbers.Find(n=> n<10);
//print all the numbers in the list to the console
numbers.ForEach(n=> Console.WriteLine(n));
//convert all the numbers in the list to floating-point values
List<float> floatNumbers=numbers.ConvertAll<float>(n=> (float)n);
//sort the numbers in reverse order
numbers.Sort((x, y) => y-x);
//filter out all odd numbers
numbers.RemoveAll(n=> n%2!=0);
// Count odd numbers
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int oddNumbers = numbers.Count(n => n % 2 == 1);
The general rules for lambdas are as follows:
     You can omit parentheses for the argument list if the expression has one argument. But if the expression has more than one argument or has no arguments, you must include the parentheses.
delegate void EmptyDelegate();
EmptyDelegate dlgt= ()=> Console.WriteLine(“Lambda without return type!”);
      You can include multiple statements if you enclose them inside a statement block:
   Action<Control> action=
·         The lambda must contain the same number of parameters as the delegate type.
·         Each input parameter in the lambda must be implicitly convertible to its corresponding delegate parameter.
·         The return value of the lambda (if any) must be implicitly convertible to the delegate’s return type.
The following rules apply to variable scope in lambda expressions:
     A variable that is captured will not be garbage-collected until the delegate that references it goes out of scope.
     Variables introduced within a lambda expression are not visible in the outer method.
     A lambda expression cannot directly capture a ref or out parameter from an enclosing method.
     A return statement in a lambda expression does not cause the enclosing method to return.
     A lambda expression cannot contain a goto statement, break statement, or continue statement whose target is outside the body or in the body of a contained anonymous function.

Leave a Reply