Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot convert from 'void' to 'System.Action' [duplicate]

Tags:

c#

action

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));     
}
like image 590
TheColonel26 Avatar asked Mar 28 '18 14:03

TheColonel26


2 Answers

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());
like image 128
DavidG Avatar answered Oct 21 '22 07:10

DavidG


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.

like image 35
Patrick Hofman Avatar answered Oct 21 '22 07:10

Patrick Hofman