Implementing an interface with a subclass of the required class/interface

Say I have an interface IDatasource that has a method signature that lets you make a Request and get a Response:

public interface IDatasource { Response GetData(Request request); } 

IDatasource has two implementations, AnalogDatasource and DigitalDatasource:

public class AnalogDatasource:IDatasource { //code goes here } public class DigitalDatasource:IDatasource { //code goes here } 

Both IDatasource implementations require a slightly different implementation of Request, so what I would like to do is something like this, where you have an AnalogRequest and a DigitalRequest class that implements Request, where Request is either an abstract class or an interface:

public class AnalogDatasource:IDatasource { //code goes here public Response GetData(AnalogRequest request) { //more code } } public class DigitalDatasource:IDatasource { //code goes here public Response GetData(DigitalRequest request) { //more code } } public interface IRequest { //code goes here } public class AnalogRequest:IRequest { //code goes here } public class DigitalRequest:IRequest { //code goes here } 

The problem is that when I try to do this, I am told that AnalogDatasource and DigitalDatasource don't implement IDatasource because the signature of GetData doesn't match the signature that's defined in the interface. I've played around with different ways of doing this, but nothing seems to work the way I want it to.

How can I structure my code in a way that allows me to have two different implementations of Request/IRequest, and enforce the use of these in the different subclasses to make sure that an AnalogRequest can't be made to a DigitalDatasource and vise versa?

by g2petter via /r/csharp

Leave a Reply