Guerrilla Guerrilla - 3 months ago 30
C# Question

Get the type of class to use in generic parameter

I am trying to make a method that accepts any model to be bound to a Json response but I can't work out how to dynamically insert the type of class model into the generic parameter.

This is what I've got so far:

public static async Task<object> DoPost(string url, FormUrlEncodedContent formEnc, object model)
{
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.PostAsync(url, formEnc))
using (HttpContent content = response.Content)
{
var result = await content.ReadAsStringAsync();
var modelType = model.GetType();
model = JsonConvert.DeserializeObject<modelType>(result);

return model;
}
}


How do I get the proper representation of type into
modelType
?

Answer

This can be simply changed to a Generic such as below. Then your Generic can be easily deserialized out.

public static async Task<T> DoPost<T>(string url, FormUrlEncodedContent formEnc)
{
    using (HttpClient client = new HttpClient())
    using (HttpResponseMessage response = await client.PostAsync(url, formEnc))
    using (HttpContent content = response.Content)
    {
        var result = await content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<T>(result);
    }
}

Now this can be called with any type of model as the generic parameter. This can be called now just passing in the Generic paramter as T such as:

 var user = DoPost<User>(url, formEnc);