3

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

Dmytro Shevchenko
  • 33,431
  • 6
  • 51
  • 67
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
  • 1
    Given that Func is defined 17 ways Func to Func I believe is a strong indicator that what you want cannot be done. Otherwise MSFT would have done it that way. – Clay Ver Valen Oct 23 '15 at 11:14

3 Answers3

6

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

Dmytro Shevchenko
  • 33,431
  • 6
  • 51
  • 67
1

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 });
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
1

Essentially your anonymous type does not contain a method, but instead a property of type Func<,>. C# does not support variadic generics i.e. you can't have generic with variable number of parameters. See.

What you can do instead:

  1. For aggregate like functions consider using of IEnumerable as generic parameter for Func<,>. For example: Func<IEnumerable<int>, int>(...).
  2. Here is workaround that could be useful for you.
Community
  • 1
  • 1
Aleksei
  • 398
  • 2
  • 13