✅ is there any way to cast Task into Task<object>?

so, i have this delegate function:

public delegate object RouterCallback(HttpRequest request);


which some methods already implements it, and some of then are async that returns Task<something>, and i need that value inside that task.

for non Task<T> methods i can have it using:

object actionResult = matchedRoute.Callback(request);


and fine, but if it is Task<something> i can only determine if it is an task using:

if (actionResult is Task taskResult)


but it doens't has the .Result property since it's an Task and not Task<T>

i can unsafely cast it and get it result using

 if (actionResult is Task asyncResult)
 {
     asyncResult.Wait();

     var valueTask = Unsafe.As<Task<object>>(asyncResult);
     actionResult = valueTask.Result;
     // do something with actionResult
}


but it only works when T is an reference-type and doens't works when T is an struct/value type object.

so, I need to get the value of Task<T> actionResult when actionResult is a Task<T>, but I don't know what <T> is. how do I managed to get it?

using reflection to get the .Result property value requires a lot of resources and costs a lot of performance.
Was this page helpful?