Passing a method with a parameter to a method that accepts an Action type parameter results in the syntax error
Cannot convert from 'void' to 'System.Action'
However if I pass it a method that does not have any parameters it works fine.
I assume C#
is doing something automatically when I pass it a method without a parameter.
I would like to know what it is doing behind the scenes and how to do the same with method that has parameters.
public void Invoke(Action action){ /*Code Here */ }
public void Method1(){ /*Code Here */}
public void Method2(int param){ /*Code Here */ }
public void test()
{
int testParam = 1;
//** This works
Invoke(Method1);
//** This does not work
Invoke(Method2(testParam));
}
Your Invoke
method is expecting an Action
but you are trying to pass it the return value of a method which in this case is void
. Instead you can use a lambda to create the Action
:
Invoke(() => Method2(testParam));
Or to be more explicit:
Action a = () => Method2(testParam);
Invoke(a);
The reason the first version works for you is that passing a method without trailing ()
is shorthand for the code above. So these are equivalent:
Invoke(Method1);
Invoke(() => Method1());
Your code doesn't work because Method2(testParam)
executes the method, instead of providing an action that can be executed any time in the future.
You need a lambda here:
Invoke(() => Method2(testParam));
The other code (Invoke(Method1)
) works because you provide a delegate here to the method (note the missing parenthesis: no execution, just a reference to the method). A delegate can be converted to an action.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With