Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a generic type to a method which takes a generic type

Tags:

c#

.net

I'm trying to write a method which takes a generic type T and passing it to a method (client.Execute) which takes a generic type

private T GetResult<T>(IRestRequest request)
{
    var client = new RestClient(string.Format("{0}:{1}", ApiBase, ApiPort))
    var response = client.Execute<T>(request);
    // omitted for brevity 
}

How ever the following line dosnt compile

var response = client.Execute<T>(request);

Error 1 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method

The Execute method is defined as follows

public virtual RestSharp.IRestResponse<T> Execute<T>(RestSharp.IRestRequest request) where T : new()
like image 894
TheGeneral Avatar asked Nov 28 '25 05:11

TheGeneral


1 Answers

You have a where T : new() constraint in Execute<T>(). GetResult<T>() should have the same constraint.

like image 166
Ilian Avatar answered Nov 30 '25 19:11

Ilian