BrunoLM
BrunoLM

Reputation: 100331

Passing a lambda to a method with different parameters

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?

Upvotes: 2

Views: 267

Answers (3)

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68687

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.

Upvotes: 1

KeithS
KeithS

Reputation: 71563

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

...

Upvotes: 0

Eric Lippert
Eric Lippert

Reputation: 660038

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?

Upvotes: 6

Related Questions