Anonymous methods:
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.abutton1.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:
- We avoid overhead of writing methods for handlers or delegate by using anonymous methods whenever possible.
- They can't be explicitly called in code.
- They can't contain goto or break or continue statements where the target is out of expression or method block.
- Scope of variables in anonymous methods is method block only.
- They can't accept parameters using ref or out keyword.
- 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