Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# : how to accept two generic parameters

Tags:

c#

generics

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.

like image 385
Niharika Verma Avatar asked Jan 06 '23 01:01

Niharika Verma


1 Answers

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;
}
like image 195
Yacoub Massad Avatar answered Jan 17 '23 12:01

Yacoub Massad