Consider the following case:
class A
{
public int Id;
}
class B : A
{
}
class Main
{
public async Task Create(Type type)
{
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;
The above solution really helped me. I made a small tweak to the @Lukazoid solution...
var resultProperty = typeof(Task<>).MakeGenericType(type).GetProperty("Result");
A a = (A)resultProperty.GetValue(task);
to
dynamic a = task.GetType().GetProperty("Result")?.GetValue(task);