Generic interface with default implementations

4 days ago 6
ARTICLE AD BOX

I have this interface:

public interface IDebugEndPoint { void InstructionReady(ICPU cpu); }

where ICPU is implemented by many concrete CPU types. I pass an IDebugEndPoint to an ICPU for "stuff".

I find myself writing classes that implement IDebugEndPoint and immediately cast the ICPU to the concrete type.

I would like to create a new interface like this:

public interface IDebugEndPoint<TCPU> : IDebugEndPoint where TCPU : ICPU { void InstructionReady(ICPU cpu) => InstructionReady((TCPU)cpu); void InstructionReady(TCPU cpu); }

Classes that implement this interface would implement the strongly-typed version of InstructionReady and would be able to be passed as an IDebugEndPoint.

I have run into 2 problems:

The compiler warns me that InstructionReady(ICPU...) hides the inherited version and needs to be marked as new

Classes that implement this interface are forced to implemenrt both methods. It's as if the default implementation is ignored.

My workaround is to define a class that implements IDebugEndPoint and calls a virtual method that is strongly-typed with the generic. But I would like to avoid inheriting from this class and implement the generic interface instead.

How can I do this?

Read Entire Article