2

Is it possible to call a method passing a lambda with variable number of parameters?

For example:

public void Go(Action x)
{
}

I need to call it passing parameters, such as:

Go(() => {});
Go((x, y) => {});
Go((x) => {});

Is it possible? How?

BrunoLM
  • 97,872
  • 84
  • 296
  • 452

3 Answers3

6

Not without casting. But with casting, its easily done:

void Go(System.Delegate d) {}
...
Go((Action)(()=>{}));
Go((Action<int>)(x=>{}));
Go((Action<int, int>)((x,y)=>{}));

Out of curiosity, what is the body of Go going to do? You've got a delegate of unknown type so you don't know what arguments to pass in order to call it. How are you planning on invoking that delegate?

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
1

You could create overloads as in

public void Go<T>(Action<T> x)
{
}

Here is an article showing more examples of Action<T>. Notice that it doesn't return a value, from MSDN:

Encapsulates a method that has a single parameter and does not return a value.

BrunoLM
  • 97,872
  • 84
  • 296
  • 452
Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142
  • @Bruno, why did you edit Yuriy's post and editorialize extra content? That's not really appropriate for an edit, as it implies the author of that content is Yuriy when in fact it was you. "Edit" should be used for corrections. Instead, you should have added a comment (like this). – Kirk Woll Sep 23 '10 at 19:24
  • If I can't improve his answer I will just post my own and accept it. If he don't like the edit he can remove, and then I will create another answer. – BrunoLM Sep 23 '10 at 19:25
0

You have to strongly define the signatures of each lambda type.

public TResult Go<TResult>(Func<TResult> x) {return x()};

public TResult Go<T,TResult>(Func<T, TResult> x, T param1) {return x(param1)};

...
KeithS
  • 70,210
  • 21
  • 112
  • 164