Can params[] be parameters for a lambda expression?

Andrew Gray picture Andrew Gray · Jun 26, 2012 · Viewed 7.5k times · Source

I've recently started exploring lambda expressions, and a question came to mind. Say I have a function that requires an indeterminate number of parameters. I would use the params keyword to model that variable number of parameters.

My question: can I do something similar with Lambda expressions? For example:

Func<int[], int> foo = (params numbers[]) =>
                       {
                           int result;

                           foreach(int number in numbers)
                           {
                               result += numbers;
                           }

                           return result;
                       }

If so, two sub-questions present themselves - is there a 'good' way to write such an expression, and would I even want to write an expression like this at some point?

Answer

Nikola Anusev picture Nikola Anusev · Jun 26, 2012

Well, sort of. First, instead of using Func<>, you would need to define a custom delegate:

public delegate int ParamsFunc (params int[] numbers);

Then, you could write a following lambda:

ParamsFunc sum = p => p.Sum();

And invoke it with variable number of arguments:

Console.WriteLine(sum(1, 2, 3));
Console.WriteLine(sum(1, 2, 3, 4));
Console.WriteLine(sum(1, 2, 3, 4, 5));

But to be honest, it is really much more straightforward to stick with built-in Func<> delegates.