claydiffrient
claydiffrient

Reputation: 1306

Create and invoke generic async method

I have a situation where I need to determine the type of an object dynamically (compile time is fine) within a declaration for a generic.

I have a method like this:

private async Task<T> Post<T>(string path, Request data)
{
    var authPath = GetAuthenticatedPath(path);
    var response = await _client.PostAsJsonAsync<Request>(authPath, data);
    return response;
}

The problem is that I really need it to operate more like this:

private async Task<T> Post<T>(string path, Request data)
{
    var authPath = GetAuthenticatedPath(path);
    var response = await _client.PostAsJsonAsync<data.GetType()>(authPath, data);
    return response;
}

Because I need it to format the data variable as it's ActualRequestType rather than the Request type when it does the conversion to JSON. The problem is you can't do data.GetType() within the type declaration.

Upvotes: 1

Views: 13995

Answers (2)

Grundy
Grundy

Reputation: 13380

method PostAsJsonAsync return Task<HttpResponseMessage> so possibly you don't need return generic, only get like this

private async Task<HttpResponseMessage> Post<T>(string path, T data)
{
    var authPath = GetAuthenticatedPath(path);
    var response = await _client.PostAsJsonAsync<T>(authPath, data);
    return response;
}

Upvotes: 0

dee-see
dee-see

Reputation: 24088

Modify your signature to this:

private async Task<T> Post<T, TRequest>(string path, TRequest data)
    where TRequest : Request
{
    var authPath = GetAuthenticatedPath(path);
    var response = await _client.PostAsJsonAsync<TRequest>(authPath, data);
    return response;
}

The condition will make sure you are still receiving valid Request objects and the actual type will carry on to the PostAsJsonAsync call.

Upvotes: 6

Related Questions