5

I have the following method:

public async Task Execute()
{
    object previous = null;

    // _delegates is of type IReadOnlyCollection<Delegate>
    foreach (Delegate method in _delegates) 
    {
        Task executing = (Task) (previous != null
           ? method.DynamicInvoke(_repository, previous)
           : method.DynamicInvoke(_repository);

        await executing;

        // pseudo code here
        if (executing returns something)
           previous = executing.Result //<-- ?
        else
           previous = null;
    }
}

Basically I iterate over a list of delegates that I execute in order. Each delegate receives a repository as argument, and the return value of the previous delegate (if there was any).

Some delegates return a Task and some return a Task<TResult>. If encountered with the latter, I want to store the TResult value in previous so I can pass it as an argument to the next delegate.

Is there a way to achieve this?

Matias Cicero
  • 25,439
  • 13
  • 82
  • 154

2 Answers2

5

You can use Reflection to check if the type of the executing object is Task<T> and then read the "Result" property if so like this:

var taskType = executing.GetType();

bool isTaskOfT =
    taskType.IsGenericType
    && taskType.GetGenericTypeDefinition() == typeof(Task<>);

if (isTaskOfT)
{
    object result = taskType.GetProperty("Result").GetValue(executing);
}
Yacoub Massad
  • 27,509
  • 2
  • 36
  • 62
-3

In if you need to add casting:

if (executing returns something)
    previous = ((Task<object>)executing).Result
else
    previous = null;
Marcin Dudek
  • 170
  • 1
  • 8