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?
Core Java bootcamp program with Hands on practice The lambda expressions are easy and contain three parts like parameters (method arguments), arrow operator (->) and expressions (method body).
Passing Lambda Expressions as Arguments If you pass an integer as an argument to a function, you must have an int or Integer parameter. If you are passing an instance of a class as a parameter, you must specify the class name or the object class as a parameter to hold the object.
A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.
The body of a statement lambda can consist of any number of statements; however, in practice there are typically no more than two or three.
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.
The closest thing that I think you can get would be something like this:
Func<int[], int> foo = numbers[] =>
{
// logic...
}
var result = foo(Params.Get(1, 5, 4, 4, 36, 321, 21, 2, 0, -4));
And have:
public static class Params
{
public static T[] Get(params T[] arr)
{
return arr;
}
}
But I can't see how that beats a simple new[] {1, 5, 4, 4, ...}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With