Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous method with a variable number of parameters

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).

like image 386
MakePeaceGreatAgain Avatar asked Dec 04 '25 11:12

MakePeaceGreatAgain


2 Answers

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);

like image 112
Dmytro Shevchenko Avatar answered Dec 07 '25 00:12

Dmytro Shevchenko


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 });
like image 40
MakePeaceGreatAgain Avatar answered Dec 07 '25 01:12

MakePeaceGreatAgain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!