Await the result of Task<TDerived> using reflection in a non-generic method
As per my comment:
Unlike interfaces, concrete types such as
Task<TResult>
cannot be covariant. See Why is Task not co-variant?. SoTask<B>
cannot be assigned to aTask<A>
.
The best solution I can think of is to use the underlying type Task
to perform the await
like so:
var task = (Task)method.Invoke(this, new object[] { "humpf" });
await task;
Then you can use reflection to get the value of the Result
:
var resultProperty = typeof(Task<>).MakeGenericType(type).GetProperty("Result");
A a = (A)resultProperty.GetValue(task);
return a.Id;