Reputation: 2319
I use restsharp to consume an external API. I have a class that extends the interface
public interface ICarInfo
{
ICarDetails GetCarInfo(string car);
}
public interface ICarDetails
{
string Color { get; set; }
string MaxSpeed { get; set; }
string Acceleration{ get; set; }
}
I create the class which extends this interface and implement this method using restsharp
public ICarDetails GetCarInfo(string car)
{
var client = new RestClient("http://xxx.xxxxxxx.com");
var request = new RestRequest("/{car} ? access_key =xxxxxxxxx", Method.GET);
var queryResult = client.Get<ICarDetails >(request).Data;
return queryResult;
}
Now i get an error in this line:
var queryResult = client.Get<ICarDetails >(request).Data;
ICarDetails must be a non-abstract type with a public parameterless constructor in order to use it as a parameter T in the generic type or method
Upvotes: 1
Views: 1030
Reputation: 375
You cannot use interface in this section. In this case, you want to cast the received value into an interface that is not possible. This is because the compiler need a type to be able create instance of it and then cast recived value into instance. It actually requires a class with the parameterless constructor. You should use concrete class instead of interface to solve the problem.
Upvotes: 0
Reputation: 247153
A concrete class is needed in order to be able to deserialize the request data.
So refactor the definitions accordingly
public interface ICarInfo {
CarDetails GetCarInfo(string car);
}
public class CarDetails {
public string Color { get; set; }
public string MaxSpeed { get; set; }
public string Acceleration{ get; set; }
}
And the implementation
public CarDetails GetCarInfo(string car) {
var client = new RestClient("http://xxx.xxxxxxx.com");
var request = new RestRequest("/{car} ? access_key =xxxxxxxxx", Method.GET);
var queryResult = client.Get<CarDetails>(request).Data;
return queryResult;
}
Even if you insist on keeping the ICarDetails
interface, you will still need a concrete implementation for deserialization.
public interface ICarInfo {
ICarDetails GetCarInfo(string car);
}
public interface ICarDetails {
string Color { get; set; }
string MaxSpeed { get; set; }
string Acceleration{ get; set; }
}
public class CarDetails : ICarDetails {
public string Color { get; set; }
public string MaxSpeed { get; set; }
public string Acceleration{ get; set; }
}
Again making sure the concrete class is used
public ICarDetails GetCarInfo(string car) {
var client = new RestClient("http://xxx.xxxxxxx.com");
var request = new RestRequest("/{car} ? access_key =xxxxxxxxx", Method.GET);
var queryResult = client.Get<CarDetails>(request).Data;
return queryResult;
}
Upvotes: 1