Sunday, June 02, 2013

LINQ 03: Lambda expression

Lambda expressions provides a simpler mechanism, to create or pass delegates without creating a separate methods to be referred.

In other words, we can say lambda expressions are inline functions

 

For example consider the following

we have a delegate CalcDelegate with two integer parameters

delegate void CalcDelegate(int a, int b)

we have a method Calc requires the CalcDelegate to be passed.

int Calc(CalcDelegate, int m, int n)

To create an Add operation with this, we will create a add method

void Add(int a, int b) {return a+b;}

So that we can call the Add using Calc

Calc(Add, 1, 5);

But for using in a single location, we have to create a function for this (without lambda expressions)

With lambda expressions we can simplify this with the inline method

Calc( (a,b) => a+b, 2, 5);

 

Lambda expressions are simple to create

left side of => is the parameter section

right side of => is the body section

 

Parameter section

  • when no parameters are required for the delegate, we can use ()
    • Example: ()=> Console.WriteLine(‘no parameter method invoked’)
  • when only one parameter is required for the delegate, we can use paramName or (paramName)
    • Example: a=> a*2
  • when more that one parameters are required for the delegate, we can use (paramName1, patamName2, …)
    • Example: (a, b) => a +b
  • Parameter types are inferred with automatic type inferencing
  • When the automatic does not help, we can use explicit declaration (paramType1 paramName1, paramType2 paramName2, …)
    • Example: (int a, int b) => a + b

Body section

  • When the function has single statement, no need for open and close braces, but we can use them optionally.
    • Example: a=> a*a
  • When the function has multiple statements we should enclose them within open and close braces
    • Example: a=> { var b=a*a;  return b;}

No comments:

Post a Comment