Matias Cicero
Matias Cicero

Reputation: 26331

Passing variable arguments to a delegate

I have the following delegate:

public delegate object DynamicFunction(dynamic target, params object[] args);

However, when I try to create it:

DynamicFunction func = new DynamicFunction((t) => {
     //Handle t
});

The compiler throws an error saying that the delegate does not take 1 argument, even though I specified the last argument to be of type params object[].

If I pass exacly one extra argument to the delegate, it works. For example:

DynamicFunction func = new DynamicFunction((t,a) => {
     //Handle t
});

However, I don't want to specify that extra argument, as I intentionally wanted those arguments to be optional.

What is happening here?

Upvotes: 1

Views: 469

Answers (2)

Alexei Levenkov
Alexei Levenkov

Reputation: 100620

params mean that compiler will do smart thing when you call the function to convert whatever arguments you've passed to array.

It does not mean that function itself takes 1 or 2 parameters, and it does not mean there are 2 version of function f(dynamic target) and f(dynamic target, params object[] args).

Note that you still want to be able to call

func (1);
func(1, optional1, optional2);

So your delegate need to handle both.

Upvotes: 2

Servy
Servy

Reputation: 203815

When invoking the delegate the caller can provide 1...n arguments. What you're doing now isn't invoking the delegate, but rather assigning a compatible method to a delegate of that type. When doing so you need to provide exactly two arguments (of the appropriate type), because that's what the delegate's definition states it must accept.

Upvotes: 1

Related Questions