cannot convert from 'void' to 'System.Action'

TheColonel26 picture TheColonel26 · Mar 28, 2018 · Viewed 21.1k times · Source

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));     
}

Answer

DavidG picture DavidG · Mar 28, 2018

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());