Saruman Saruman - 2 months ago 27
C# Question

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

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

The Execute method is defined as follows

public virtual RestSharp.IRestResponse<T> Execute<T>(RestSharp.IRestRequest request) where T : new()


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