robert tonnessen
robert tonnessen

Reputation: 39

Why cant I pass a type to a generic method

Ok a brief background. I'm trying out various ways to test an API and I'm trying to allow a user to provide a simple CSV file of a API calls that my test framework can iterate over using a generic test method. I'm having trouble passing the type to my generic API call method. Allow me to demonstrate.

Given I have a method with the following basic structure

public T GetData<T>(Uri uri, HttpStatusCode expectedStatusCode)
{
        var myHttpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
        myHttpWebRequest.Accept = "application/json";
        var response = (HttpWebResponse)myHttpWebRequest.GetResponse();

        if (response.StatusCode != expectedStatusCode)
            Report.Log(ReportLevel.Failure, "ExpectedResponseCode:" + expectedStatusCode.ToString() + " ActualResponseCode:" + response.StatusCode.ToString());

        string responseString = "";

        using (var stream = response.GetResponseStream())
        {
            var reader = new StreamReader(stream, Encoding.UTF8);
            responseString = reader.ReadToEnd();
        }

        return JsonConvert.DeserializeObject<T>(responseString);
    }

I can call the above as follows without issue

Person person = _apiHelper.GetData<Person>(uri, HttpStatusCode.Ok);

However assume I now have a Type that I have acquired as follows

Type returnType = Type.GetType(typeString, true, true);

why can I not call the GetData method as follows

var result = _apiHelper.GetData<returnType>(uri, HttpStatusCode.Ok);

Visual studio simply says it cant resolve the symbol

Upvotes: 0

Views: 157

Answers (1)

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131180

Just use the JsonConvert.DeserializeType overload that accepts a type parameter instead of the generic one:

public object GetData(Type t,Uri uri, HttpStatusCode expectedStatusCode)
{
    ....
    return JsonConvert.DeserializeObject(responseString,t);
}

This is a case of the XY problem. You want to deserialize arbitrary types (problem X) and think that somehow, you need pass a generic type at runtime (problem Y), so when you get stuck ,you ask about Y.

Upvotes: 5

Related Questions