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?

3 Answers 3

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?

Sign up to request clarification or add additional context in comments.

1 Comment

You have to put the lambda expression in parenthesis. Unless of course you change the implementation.
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.

2 Comments

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

...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.