Lambda Expression
So what is a lambda expression and why are these lambda expression used for ?
As every article of me says you what and why , here as well we are going to get an answer for it .
A lambda expression is nothing but an anonymous method .
Oh really !! But what is anonymous method here ? It might be the next question which strikes you . Just follow through get an answer for it .
An Anonymous method is a method with no access modifier , no name and no return statement . But apart from this book definition we can look its snippet for a better understanding. Before that why do we use them ? Any guess ?
For convenience . We can write less code and achieve the same thing plus our code will be more readable readable . For our practical knowledge , lets take an example , lets say we would like to write a method which takes a number and returns cube of the number .
Typically , this is how we do that
Now with lambda expression we can achieve the same thing with less code , this is how we do it
number => number * number * number
This is what we call a lambda expression and this code is exactly equivalent to this Cube method . You can see it is shorter , I did want to specify access modifier , int as return type or an argument type . The compiler can automatically infer that in most cases and if not we can explicitly specify that . I also didn't have to write the return statement here .
So what we need to is we need assign that to delegate . Remember what a delegate is ? Delegate is a pointer or reference to a method or a group of methods . In .NET we have some built in delegates , for example FUNC and ACTION . To Check Delegate click here - Delegates.
A lambda expression can be written in two forms :
Expression Lambda , that has expression as body.
() => number * number; //With No arguments
number => number * number ; // With one arguments
(number , times) => number * times // With two arguments
Statement Lambda , which has a set of statements as a body .
Func<int,int,int> output = (number , times) => {
int a = number + 10;
a*times;
}
Incorporating asynchronous programming into the lambda expression is pretty simple using async and await keywords.
async (filename) => {
var file = await DownloadAsync(filename);
}
Starting with C# 7.0 , lambda expression even supports tuples which can take tuple as an argument and return tuple as its result .
More information available at : Lambda Expression
Comments
Post a Comment