c# lambda expression |
LAMBDA EXPRESSION IN C#
“Lambda expression is just a short hand for write the
anonymous method, means it is a simple method to write an anonymous method”. Lambda expression is represented by =>
(Equal in sense of math and assignment operator in programming and then greater
then operator) see the example for better understanding.
It will better understand if you
have clear idea about anonymous method. In anonymous we taught about the
removing of method defining and then binding with the delegate separately,
simple and straight we defined and bound the unnamed method by the time of
creating delegate instance. Like this
<Delegate-name>
Obj = delegate (parameter list)
{
Method implementation;
} ;
syntax of lambda expression is slightly change that is bellow.
Syntax of lambda expression
1. It’s also included in three steps 1st step define
delegate under name space of same signature that would be the method signature.
2. In 2nd step using lambda expression define method and
bind with thedelegate.
3. And 3rd step call the method using the name of
delegate.
All the steps that included in
anonymous method defining, calling and instance creating. Lambda expression
syntax is also same like that but here by bringing a little bit change in
anonymous method syntax of creating instance we will make the lambda expression
syntax but the remaining two steps that include the defining of delegate under
namespace and calling will still same. Have a look to the above anonymous
method syntax and then see this
<Delegate-name>
Obj = (parameter name) =>
{
Method implementation;
} ;
We remove the delegate keyword and
data type form the anonymous method and use => in place of that that makes
the codding easier and time saving but it will work like anonymous method
that’s why lambda is called as the short hand writing for anonymous method.
EXAMPLE OF LAMBDA EXPRESSION IN C#
Suppose we
have a method that accept name and generate some greeting with help of lambda
expression
Main
program
namespace
LambMethod
{
public delegate string GreetDelegate(string
str); //defining delegate stage 1
class Program
{
static void Main(string[] args)
{
GreetDelegate Obj = (str) => //lambda expression defining stage 2
{
return "Hello " + str
+ " Welcome to Newmountain Hotel";
};
Console.WriteLine(Obj("Asif")); //calling delegate/anonymous method S-3
Console.ReadKey();
}
}
}
0 comments:
Post a Comment
Please do not enter any spam link in the comment box