C# - transform an async task from one type to another
The most direct translation with existing methods would be:
Task<int> statusCode = response.ContinueWith(t => t.Result.StatusCode)
However in practice you almost always await the task to get the result. Maybe you should look into async/await.
I'm slightly surprised there isn't anything in the framework for this, to be honest. (More likely, there is an I haven't seen it.) You can build it fairly easily though:
public static async Task<TResult> Map<TSource, TResult>
(Task<TSource> task, Func<TSource, TResult> selector)
=> selector(await task.ConfigureAwait(false));
Note: using ConfigureAwait
here isn't always clear-cut. You may want to include a continueOnCapturedContext
parameter:
public static async Task<TResult> Map<TSource, TResult>(
Task<TSource> task,
Func<TSource, TResult> selector,
bool continueOnCapturedContext = false) =>
selector(await task.ConfigureAwait(continueOnCapturedContext));