Jorn Theunissen
Jorn Theunissen

Reputation: 191

Generic method returning generic type

I am using a restclient that accepts a type, which is later converted to the correct IRestResponse.

IRestResponse<MyClassA> response = client.Execute<MyClassA>();

Since MyClassA can also be MyClassB or MyClassC I thought about making a generic method which could handle this. However without any luck. This is my attempt:

public interface IRestClient{ IRestResponse response = PerformExecuteClient()

private RestResponse<T> PerformExecuteClient<T>() {
    return client.Execute<T>();
}

The compiler tells me that client.Execute<T> does not accept abstract types. Which makes sense, but I have no idea how else to make this method. Is it possible what I am trying to achieve here?

Additional information based on some comments. As Brains Mains suggested, the method is not accepting the abstract type here.

public interface IRestClient{
    IRestResponse<T> Execute<T>(IRestRequest request) where T : new();
}

Upvotes: 5

Views: 2030

Answers (4)

romain-aga
romain-aga

Reputation: 1561

Did you try this:

private RestResponse<T> PerformExecuteClient<T>() where T : new()
{
    return client.Execute<T>();
}

As everyone pointed out here, you have to follow the interface's generic constraint to make this work. If you don't, you do not respect the interface contract by passing an unexpected type.

Also where T : new() means that you can instantiate T like this new T(). But by definition, an abstract class can't be instantiate, that is why you get this error.

Upvotes: 2

Fabjan
Fabjan

Reputation: 13676

This :

where T : new();

Means that T will be created inside of method. But how can you create instance of abstract class ? Hence an error.

Upvotes: 1

Gilad Green
Gilad Green

Reputation: 37299

The signature is:

IRestResponse<T> Execute<T>(IRestRequest request) where T : new();

The generic constraint of new does not allow abstract classes. Instead you can:

  1. Have an interface for your classes and have a generic constraint on that.
  2. Change your MyClassA to not being abstract
  3. Remove the constraint

Me personally - I'd say the interface option - but this is opinion based :)

In any case for the PerformExecuteClient<T> it must follow at least the generic constraints of the Execute<T> which it executes.

Upvotes: 5

Brian Mains
Brian Mains

Reputation: 50728

The Execute method on the client object could have a where T: [Something] constraint, which your generic method would also need to apply. Look at the source code (if possible) or documentation to see if a where constraint is applied to the generic.

Upvotes: 0

Related Questions