I am trying to invoke Invoke on a Dispatcher using the following overload:
public object Invoke(Delegate method, params object[] args);
I want to use named arguments, but I can’t seem to find the syntax for the argument with the params modifier. All of the following won’t compile:
dispatcher.Invoke(method: () => { }, args: {});
dispatcher.Invoke(method: () => { }, args: new object[0]);
dispatcher.Invoke(method: () => { }, args: null);
dispatcher.Invoke(method: () => { }, args: new object[] {});
object[] foo = {};
dispatcher.Invoke(method: () => { }, args: foo);
dispatcher.Invoke(method: () => { }, args: new[] {"Hello", "World!"});
I found these two questions to which there seems to be no definite answers:
How to set named argument for string.Format?
So my question is: can it be done or not? If yes, how?
UDPATE
Daniel Hilgarth’s shows that yes params can be used with named parameters. I integrated his answer using this pattern:
Action method = () => { };
if (_dispatcher != null)
_dispatcher.Invoke(method: method, args: null);
else
method();
The following code compiles without problems:
I had to change the type of the first parameter from
DelegatetoActionto make it compile, because() => {}can’t be converted toDelegate.Alternatively, the following does also compile:
My assumption is that you never got a compile error about the
argsparameter but about themethodparameter saying “Cannot convert from ‘lambda expression’ to ‘System.Delegate’“. This problem is solved by either casting the lambda to an Action (Invoke(method: (Action)(() => {}) ...) or by defining a variable of typeActionthat is passed as parameter to the method (see above), becauseActioncan implicitly be converted toDelegate.