Basically, I'm trying to do something like this:
SomeRequest request = new SomeRequest();
SomeResponse response = request.GetResponse();
List<Stuff> stuff = response.GetData();
SomeRequest and SomeResponse are classes that both implement the IRequest and IResponse interfaces respectively:
public class SomeRequest : IRequest<SomeResponse>
{
public SomeResponse GetResponse() { ... }
}
public class SomeResponse : IResponse<List<Stuff>>
{
public List<Stuff> GetData() { ... }
}
My IResponse interface looks like this:
public interface IResponse<T>
{
T GetData();
}
The issue I'm running into is with my IRequest interface. I want my IRequest interface's generic (T) to be of type IResponse< T >.
public interface IRequest<T> where T : ?????
{
T GetResponse();
}
I can't figure out what I'm supposed to put after the "where T".
I found two solutions here: C# generic "where constraint" with "any generic type" definition?
The first solution is to specify IResponse< T> generic's type in IRequest like so:
public interface IRequest<T, U> where T : IResponse<U>
but that seems weird because the Request should only have knowledge of the Response and not the type that Response is supposed to return on GetData().
The second option is to create a non-generic interface IResponse and use that in IRequest's generic type constraint, which would look something like this:
public interface IResponse { }
public interface IResponse<T> { ... }
public interface IRequest<T> where T : IResponse
{
BaseResponse GetResponse();
}
This solution however caused a compile error in my SomeRequest class:
public class SomeRequest : IRequest<SomeResponse>
{
public SomeResponse GetResponse() { ... }
}
Error CS0738: SomeRequest
does not implement interface member IRequest<SomeResponse>.GetResponse()
and the best implementing candidate SomeRequest.GetResponse()
return type SomeResponse
does not match interface member return type IResponse
So now I'm out of ideas. Any help would be greatly appreciated!