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
- Statement Lambda -Statement lambda has a statement block on the right side of the lambda operator “=>”.
x => { return x * x; };
- 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); } } //output: 6 9 12