Lambda Expression (=>):
A lambda expression is an unnamed method written in place of a delegate instance.
The compiler immediately converts the lambda expression to either
- Delegate Instance
- Unmanaged Method
- Lambda Expression it introduced in C# 3.0
Below is delegate method declaration
public delegate int AddTwoNumberDel(int fvalue, int svalue);
We can use lambda expression
AddTwoNumberDel AT = (a, b) => a + b;
int result= AT(1,2);
MessageBox.Show(result.ToString());
Before that what we used Please check this url
http://jsdotnetsupport.blogspot.com/2011/08/beginner-delegate-program.html
What is Syntax in Lambda Expression?:
A lambda expression has the following form:
(parameters) => expression-or-statement-block
(a, b) => a + b; this program
(a, b) èParameter
a+b è Expression /statement block
=> è Lambda Expression
You can write Following format also
(a, b) =>{ return a + b }
Func ,Action Keyword:
Lambda Expression mostly used Func and Action Keyword
- Func Keyword is one of the generic Delegate
Example 1:
Func<int, int,string> Add = (fvalue, svalue) => (fvalue + svalue).ToString();
MessageBox.Show(Add(3, 5)); // outPut 8
Example 2:
Func<int, int, int> Add = (fvalue, svalue) => fvalue + svalue;
MessageBox.Show(Add(3, 5).ToString()); // outPut 8
Above program how its working ?
Func è Func is Keyword
Func<int, int,string> è first Two type is parameter ,Last type is return type
Add è Add is Method Name
(fvalue, svalue èParameter
(fvalue + svalue).ToString(); è Statement
Other feature:
- You can access outer variable also
Ex:
Int value=50;
Func<int, int, int> Add = (fvalue, svalue) => fvalue + svalue+ value;
MessageBox.Show(Add(3, 5).ToString()); // outPut 58
Question ?
Int value=50;
Func<int, int, int> Add = (fvalue, svalue) => fvalue + svalue+ value;
Int value=100;
MessageBox.Show(Add(3, 5).ToString());
Int value=200;
Post your Answers ….Get Special Gift …. To Bloger…..
Action Keyword:
Action Type same like Func method but The Action type receives parameters but does not return a parameter. The Func type, however, receives parameters and also returns a result value. The difference is that an Action never returns anything, while the Func always returns something. An Action is a void-style method in the C# language
Example:
using System;
class Program
{
static void Main()
{
// Example Action instances.
// ... First example uses one parameter.
// ... Second example uses two parameters.
// ... Third example uses no parameter.
// ... None have results.
Action<int> example1 =
(int x) => MessageBox.Show("Write {0}", x);
Action<int, int> example2 =
(x, y) => MessageBox.Show ("Write {0} and {1}", x, y);
Action example3 =
() => MessageBox.Show ("Done");
// Call the anonymous methods. Or example1(1)
example1.Invoke(1);
example2.Invoke(2, 3);
example3.Invoke();
}
}
Output
Write 1
Write 2 and 3
Done
No comments:
Post a Comment