36

I understand a lambda expression is in essence an inline delegate declaration to prevent the extra step

example

delegate int Square(int x)
public class Program
{
   static void Main(String[] args)
   {
      Square s = x=>x*x;
      int result = s(5);
      Console.WriteLine(result); // gives 25
   }
}

How does one apply Lambda expressions to multi parameters Something like

 delegate int Add(int a, int b)
 static void Main(String[] args)
 {
    // Lambda expression goes here
 }

How can multi parameters be expressed using Lambda expressions?

3 Answers 3

53

You must understand the Func behavior, where the last parameter is always the output or result

Func<1, 2, outPut>

Func<int, int, int> Add = (x, y) => x + y;

Func<int, int, int> diff = (x, y) => x - y;

Func<int, int, int> multi = (x, y) => x * y;
Sign up to request clarification or add additional context in comments.

2 Comments

could someone elaborate, cant understand.
@Augustas Func<int, int, bool> => (x,y) => x == y; // this will return the true or false in the third bool variable in the func. x and y are the first two ints in the func.
15

Yes. When you have other-than-one (zero, or > 1) lambda arguments, use parenthesis around them.

Examples

Func<int, int, int> add = (a,b) => a + b;

int result = add(1, 3);

Func<int> constant = () => 42;

var life = constant();

Comments

2
delegate int Multiplication(int x, int y)
public class Program
{
   static void Main(String[] args)
   {
      Multiplication s = (o,p)=>o*p;
      int result = s(5,2);
      Console.WriteLine(result); // gives 10
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.