4

I have the following interface and class:

interface IMyInterface
{
    void A();
   
    void B() 
    { 
        Console.WriteLine("B"); 
    } 
}

class MyClass : IMyInterface
{
    public void A()
    {
        Console.WriteLine("A");
    }
}

I'd like to instantiate MyClass and call B() like so:

MyClass x = new MyClass();
x.B();

However, this doesn't work since MyClass does not contain a definition for 'B'. Is there anything I can add to MyClass so this code calls the default implementation of B() in IMyInterface?

I understand the code below works, but I don't want to change the data type from MyClass to IMyInterface.

IMyInterface x = new MyClass();
x.B();
2
  • 2
    No, there is nothing you can do. That's not how default implementations work. They don't add anything to the class. You can inherit from a base class that provides that method, but the interface doesn't make that method available through a class reference. Commented Sep 29, 2021 at 21:17
  • 2
    @LasseV.Karlsen That's really unfortunate. This is how default implementations work in other languages like Kotlin. Commented Sep 29, 2021 at 21:40

3 Answers 3

3

You can call it like:

MyClass x = new MyClass();
(x as IMyInterface).B();
Sign up to request clarification or add additional context in comments.

Comments

3

Maybe this is a bit of a hack, but you could use a class extension to add the B() method to every class that implements IMyInterface.

static class ImplIMyInterface
{
    public static void B(this IMyInterface obj) => obj.B();
}

Now you can call B() on an instance of MyClass.

Comments

2

you can't do that. you must implement the interface that your class has inherited from it. but you can use abstract class instead of interface. like this:

 abstract class MyAbstract
{
    public void A() { }

   public void B()
    {
        Console.WriteLine("B");
    }
}

class MyClass : MyAbstract
{
    public new void A()
    {
        Console.WriteLine("A");
    }
}

var x = new MyClass();
    x.B();

Comments

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.