Question

Why doesn't:

delegate void MyDelegate(params object[] parameters);
static void ShouldMatch() {}
MyDelegate compilerError = ShouldMatch;

Compile? It seems like it should match just fine.

Was it helpful?

Solution

The delegate, MyDelegate defines a method that takes an array of objects, but your ShouldMatch method does not. Suppose you try to pass any parameters to an instance of your delegate like this:

compilerError(someObject, someOtherObject);

If the method compilerError is bound to does not accept any parameters, what would you expect to happen here?

Try defining your method in a way that matches the delegate signature:

delegate void MyDelegate(params object[] parameters);
static void ShouldMatch(params object[] parameters) {}

MyDelegate noCompilerError = ShouldMatch;

Or you could try wrapping it in a lambda expression, like this:

delegate void MyDelegate(params object[] parameters);
static void ShouldMatch() {}

MyDelegate noCompilerError = (paramArray) => ShouldMatch();

OTHER TIPS

params is a purely compile-time feature.
Delegate binding ignores it.

Your delegate must match the method's parameters exactly, ignoring params & optional parameters.

The spec states this explicitly, in §6.6:

o The candidate methods considered are only those methods that are applicable in their normal form (§7.5.3.1), not those applicable only in their expanded form.

§7.5.3.1 says:

For a function member that includes a parameter array, if the function member is applicable by the above rules, it is said to be applicable in its normal form. If a function member that includes a parameter array is not applicable in its normal form, the function member may instead be applicable in its expanded form:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top