Dbl Dbl - 3 years ago 61
C# Question

How to wrap a generic method into a non generic one?

public async Task QueueCallAsync(Task apiCall, RequestType requestType)
{
// how do you forward the call to the generic implementation while omitting the result?
await QueueCallAsync<Void>(apiCall, requestType);
}

public async Task<T> QueueCallAsync<T>(Task<T> apiCall, RequestType requestType)
{
}


So far all i achieved was recursive calls or non compilable code. I would rather wrap the generic implementation instead of duplicating the code.

Does anyone know how to tell the c# compiler to use the generic method here?

Unlike other questions I am wondering if there is a built in, intended way, to solve this without the use of reflection.

I would rather copy paste code than reflect in this case.

Answer Source

You can simply wrap task into another that returns fake int value:

async Task<int> Wrap(Task t)
{
    await t;
    return 42;
}

await QueueCallAsync<int>(Wrap(apiCall), requestType);

Side note: method name you use could be confusing for users of the method as generally tasks are already running when created and it is too later to "queue" them...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download