tronman
tronman

Reputation: 10115

C# call interface method with default implementation

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();

Upvotes: 4

Views: 390

Answers (3)

Rubix Cube
Rubix Cube

Reputation: 118

You can call it like:

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

Upvotes: 3

ZeHasNoName
ZeHasNoName

Reputation: 31

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.

Upvotes: 3

Shohreh Mortazavi
Shohreh Mortazavi

Reputation: 224

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();

Upvotes: 2

Related Questions