Thursday, January 15, 2015

Anonymous Method and Lambda Expression

What is anonymous method?
Ans. The concept of anonymous method was introduced in C# 2.0. An anonymous method is an inline unnamed method in the code. It is created using the delegate keyword and doesn’t have its name and return type.
In this way, an anonymous method has no name, optional parameters and return type; it has only body. An anonymous method behaves like a regular method and allows you to write inline code in place of regular method.



class Program {
 //delegate for representing anonymous method
delegate int del(int x, int y); static void Main(string[] args)
 { //anonymous method using delegate keyword
del d1 = delegate(int x, int y)
 { return x * y; };
 int z1 = d1(2, 3);
 Console.WriteLine(z1); } }




Key points about anonymous method
1. A variable, declared outside the anonymous method can be accessed inside the anonymous method.
2. A variable, declared inside the anonymous method can’t be accessed outside the anonymous method.
3. We use anonymous method in event handling.
4. An anonymous method, declared without parenthesis can be assigned to a delegate with any signature.
5. Unsafe code can’t be accessed within an anonymous method.
6. An anonymous method can’t access the ref or out parameters of an outer scope.



What is lambda expression?
Ans. The concept of lambda expression was introduced in C# 3.0. Typically, lambda expression is a more concise syntax of anonymous method. It is just a new way to write anonymous method. At compile time all the lambda expressions are converted into anonymous methods according to lambda expression conversion rules. The left side of the lambda operator "=>" represents the arguments of anonymous method and the right side represents the method body.
Lambda expression Syntax



(Input-parameters) => expression-or-statement-block
Types of Lambda expression
1. Statement Lambda -Statement lambda has a statement block on the right side of the lambda operator "=>". x => { return x * x; };
2. Expression Lambda - Expression lambda has only an expression (no return statement or curly braces), on the right side of the lambda operator "=>".

x => x * x; // here x*x is expression


Anonymous Method and Lambda Expression example:
 class Program { //delegate for representing anonymous method
delegate int del(int x, int y);
static void Main(string[] args)

{ //anonymous method using expression lambda
del d1 = (x, y) => x * y; //
 or (int x, int y) => x * y;
//anonymous method using statement lambda del d2 = (x, y) => { return x * y; };
 // or (int x, int y) => { return x * y; };
//anonymous method using delegate keyword
del d3 = delegate(int x, int y)
 { return x * y; };
int z1 = d1(2, 3);
 int z2 = d2(3, 3);
int z3 = d3(4, 3);
 Console.WriteLine(z1);
 Console.WriteLine(z2);
 Console.WriteLine(z3);
 } } /

No comments:

Post a Comment