Wednesday, January 23, 2013

Anonymous Methods, Lambda Expressions, lamda vs anonymous and their advantages

Anonymous methods:


Anonymous methods are introduced in .NET 2.0. Anonymous methods are inline methods with no name that can be directly assigned to a delegate. These methods are set of statements without any special syntax as in lambda expressions.

Advantages of anonymous methods over lambda are:

 They can be assigned/converted to delegate of any signature. They do no need parameter list to be mentioned like in lambda expressions.

Examples:

 Example 1.a

button1.Click += delegate(System.Object o, System.EventArgs e)
                   { System.Windows.Forms.MessageBox.Show("Click!"); };
Example 1.b
delegate int Square(int k);
Square d = new delegate(int k){return k*k;};

Common for Both Lambda and Anonymous methods:

  1. We avoid overhead of writing methods for handlers or delegate by using anonymous methods whenever possible. 
  2. They can't be explicitly called in code. 
  3. They can't contain goto or break or continue statements where the target is out of expression or method block.
  4.  Scope of variables in anonymous methods is method block only.
  5.  They can't accept parameters using ref or out keyword.
  6.  They can use variable declared outside their scope and such variable are called outer variables.

Lambda Expressions:


Lambda expressions are introduced in C# 3.0. They are used to instantiate a delegate by an inline method. This inline method will contain lambda (=>) after the input parameter list and statement to the right of lambda symbol. 

(input parameters) => expression

By using lambda expressions we can write local methods that can be passed as arguments that expect delegate as an argument.
    
     (x) => x? 5:0;

  () => SomeMethod() //zero parameters

Here, x is the input parameter. 

Statement lambda is similar to lambda expressions where in set of statements to the right of lambda are enclosed in {} and parameter list is to the left of lambda operator. 

      (input parameters) => {statement;}

Lambda expression can only be used to instantiate delegate of particular signature.

The general rules for lambdas are as follows:

  • 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.







No comments:

Post a Comment