I have the following code that creates an instance of an anonymous type having a method as the only member:
var test = new {
f = new Func<int, int>(x => x)
};
I want to implement a function that sums up all of its parameters, regardless of how many are passed. This is how a normal method would look like:
int Sum(params int[] values) {
int res = 0;
foreach(var i in values) res += i;
return res;
}
However, I don´t know if this would work for anonymous methods. I tried out Func<params int[], int>, but obviously that won´t compile. Is there any way to write an anonymous method with a variable list of parameters, or at least with optional args?
EDIT: What I´d like to achieve is to call the (anonymous) sum-method like this: test.Sum(1, 2, 3, 4).
In order to achieve this, first you need to declare a delegate:
delegate int ParamsDelegate(params int[] args);
And then use it when assigning the method property of your anonymously typed object.
var test = new {
Sum = new ParamsDelegate(x => x.Sum()) // x is an array
};
Then you have two ways of calling this method:
1) int sum = test.Sum(new [] { 1, 2, 3, 4 });
2) int sum = test.Sum(1, 2, 3, 4);
One option that comes to my mind is to simply use an array (or any other sort of IEnumerable) as type-parameter for the function:
f = new Func<IEnumerable<int>, int> ( x => foreach(var i in x) ... )
Simlar to the appraoch of Dmytro (which I prefer more) we´d call it by creating an array:
var s = test.f(new[] { 1, 2, 3, 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