Search code examples
c#delegatesinversion-of-control

Get Result from Invoke Method from Action Delegate C#


Is there a way to get the result from the invoke method in the generic action delegate?

Code Execution

public string TestRun()
{
   ExecuteService<SomeClass>(e => e.ExecuteMethod(), out var result);
   return result; // return the value;
}

Class Method

public class SomeClass
{
    public string ExecuteMethod()
    {
        return "Hello!?";
    }
}

Method of executing a generic action delegate

protected internal void ExecuteService<TAction>(Action<TAction> action, out Response response) where TAction : new()
{
    action?.Invoke(new TAction()); // invoke
    response = action?.something() // problem... how to get the value from this point forward
}

How to get the returned value from this method ExecuteMethod() inside the action delegate ExecuteService<> method and assigned it to the out value? Is this achievable?


Solution

  • You do it by not using an Action. Actions in C# are a delegate that return void, i.e nothing. If you need a return value from a delegate use either Func or if you need it to specifically return a boolean use Predicate. Like this:

    protected internal void ExecuteService<TAction>(Func<TAction> action, out Response response)
    {
        response = action?.Invoke();
    }
    

    If you need the inner the action to take parameters, use one of the other Func classes like this one which takes 1 parameter and returns T