2

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:

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

  2. 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?

0

1 Answer 1

6

If I understand the goal correctly - you can use explicit interface implementation here:

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

Example:

new DebugEndPoint().InstructionReady(new MyCpu()); // Prints "MyCpu"
((IDebugEndPoint) new DebugEndPoint()).InstructionReady(new MyCpu()); // Prints "MyCpu"

public interface IDebugEndPoint
{
    void InstructionReady(ICPU cpu) => Console.WriteLine("base");
}

public class DebugEndPoint : IDebugEndPoint<MyCpu>
{
    public void InstructionReady(MyCpu cpu)
    {
        Console.WriteLine("MyCpu");
    }
}

Demo @sharplab.io

From the Default interface members: Interface inheritance section of the doc:

When an interface overrides a method implemented in a base interface, it must use the explicit interface implementation syntax.

Sign up to request clarification or add additional context in comments.

2 Comments

This is EXACTLY what I needed! Thank you so much!!
Was glad to help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.