A lambda expression is an anonymous function. Using lambda expression we can create function for delegate and we can also create expression tree type.
Input parameter=>programming statements
If you know how to use delegate then you know we have to pass the reference of method to that delegate which matches the signature. But when we use lambda expression we can give the definition of that method directly to the delegate which is as follows:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//create a delegate which take one int as input and return one int
public delegate int Del_example(int x);
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//create object of delegate and instead passing the ref of method i simply pass
//the complete definition using lambda expression
Del_example cal_square = x => x * x;
//execute the delgate
int res=cal_square(5);
Response.Write(res);
}
}
In this example we are calculating the power using lambda expression
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//create a delegate which take one int as input and return one int
public delegate int Del_example(int x);
//create another delegate to calculate power
public delegate int del_Power(int b, int p);
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//create object of delegate and instead passing the ref of method i simply pass
//the complete definition using lambda expression
Del_example cal_square = x => x * x;
//execute the delgate
int res=cal_square(5);
Response.Write(res);
//this is another exampel of lembda expression
//power calculation
del_Power dp = (b, p) => {
//as you can see we create variable in lembda expression
int data = 1;
for (int i = 1; i < p; i++)
{
data = data * b;
}
return data;
};
int res_power = dp(3, 5);
Response.Write(res_power);
}
}
For any query you can send mail at info@techaltum.com Thanks