I have a function which I want to convert the below Ping and Pong to generic type. Is it possible?
private Pong ReadDataFromApi(string url, Ping data)
{
string url = "URL_TO_HIT";
WebResponse response = Util.SendWebRequest<Ping>(url, data, 30000);
var res = new Pong();
if (response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
var objText = reader.ReadToEnd();
res = JsonConvert.DeserializeObject<Pong>(objText);
}
}
return res;
}
I could convert to something below :
private T ReadDataFromApi(string url, T data) T : class
{
string url = "URL_TO_HIT";
WebResponse response = Util.SendWebRequest<T>(url, data, 30000);
var res = new Pong();
if (response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
var objText = reader.ReadToEnd();
res = JsonConvert.DeserializeObject<Pong>(objText);
}
}
return res;
}
Not sure how to accept the Pong as a generic parameter.
Something like this should work:
private TPong ReadDataFromApi<TPing, TPong>(string url, TPing data)
where TPing : class
where TPong : class,new() //You need to create instances of TPong
{
WebResponse response = Util.SendWebRequest<TPing>(url, data, 30000);
var res = new TPong(); //Create instance of TPong
if (response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
var objText = reader.ReadToEnd();
res = JsonConvert.DeserializeObject<TPong>(objText);
}
}
return res;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With