Lambda Expressions
Lambda Expressions
Lambda Expressions
Generic Delegates Func <> Delegates Action <> Delegates Predicate <> Delegates
Anonymous Methods: Without declaring the method, the method can be encapsulated in a delegate block. This is the preferred way to write inline code. 1) Declare a delegate delegate int sampleDelegate(int i , int j); 2) Create a instance of delegate and encapsulate the method in a delegate block sampleDelegate objDelegate = new sampleDelegate (delegate(int i, int j) { return i + j; }); int result = objDelegate (2, 3); // result= 5 Lambda Expressions: A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types. All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * x is read "x goes to x times x." This expression can be assigned to a delegate type as follows: delegate int sampleDelegate(int i); sampleDelegate objDelegate = x => x + x; int result = objDelegate (5); //result = 10
Func<int, int, int> newDelegate = (i, j) => i + j; int result = newDelegate.Invoke(2, 3);
Here delegate int sampleDelegate(int i , int j); is not declared to invoke the method . In build Func Delegate is available to invoke the method. Func delegate provides 17 overloaded methods. Example from Framework Any method takes Func
Action <> Delegates: Action delegate is ready made delegate and can be specified input and no output parameters. Action<string> objActionDelegate = y => Console.WriteLine(y); objActionDelegate("Test Action Delegate");
Predicate <> Delegates : Predicate delegate is a extension to Func delegates. It is for checking purpose and returns true or false Predicate<int> CheckLowerDelegate = y => y > 6; bool result= CheckLowerDelegate(7); Example from Framework Find takes the predicate