Reputation: 1211
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?
Upvotes: 0
Views: 1401
Reputation: 7950
You do it by not using an Action
. Action
s 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
Upvotes: 1