An anonymous function can be created in another way that is called Lambda Expressions. The lambda expression provides a powerful alternative to the anonymous method.
The Lambda Operator
All lambda expressions use the new lambda operator, which is denoted by the symbol =>. This operator divides a lambda expression into two parts. On the left the input parameter (or parameters) is specified. Right hand side is the body of the lambda. The => operator is sometimes pronounced as “goes to” or “becomes.” There are two types of lambda expression in C#. What type of lambda expression is created, it is determines by the lambda body. The two types are
• Expression lambda
• Statement lambda
An expression lambda contains single expression. In this case, the body is not enclosed between braces. Statement lambda contains block of statements enclosed by braces. A statement lambda can contain multiple statements and include loops, method calls, and if statements.
Example:
using System;
namespace Test
{
delegate int Increment(int n);
// a delegate that takes an int argument
class SimpleLambdaDemo
{
static void Main()
{
// Create an Increment delegate instance that refers to
// a lambda expression that increases its parameter by 3.
Increment incr = count => count + 3;
// Now, use the incr lambda expression.
Console.WriteLine("Use increment lambda expression: ");
int x = 10;
while (x <= 20)
{
Console.Write(x + " ");
x = incr(x); // increase x by 3
}
Console.WriteLine("\n");
}
}
}