0

I am trying the new features of C#8 and i have come to this problem. Having an interface with a default implementation method , i am defining a derived class that calls the said method inside it (constructor or proprietary method). Why am i not able to see the interface method ?

Interface with default implementation method

interface IA{
   public void DoStuff()
   {
   }
}

Derived class that should contain interface method

class A:IA
{
   public void DoSomeOtherStuff()
   {
      this.//DoStuff() does not exist !!!
      // I could write like below but it beats the purpose
      // IA a=this;
     //  a.DoStuff()
   }
}

My question is , why isn't this treated as abiding to the interface contract? Why does it not have access to the default impl method ?

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Bercovici Adrian
  • 8,794
  • 17
  • 73
  • 152
  • That's how it was designed, default interface implementation is meant to be there to allow devs to add methods to an interface without breaking clients. – DavidG Mar 11 '20 at 13:38
  • 1
    There's a very good reason for this - if multiple interfaces have the same method, the compiler (and the developer) would have no idea which one to call. That's what makes inheritance in C++ so painful. You need to access those implementations the same way you would explicit interface implementations, by first casting to the interface – Panagiotis Kanavos Mar 11 '20 at 13:40
  • So i can not access defualt imp methods from derived classes unless i cast `this` to the target interface. – Bercovici Adrian Mar 11 '20 at 13:43
  • 1
    That's what the docs and the duplicate says. If you think about it a bit, you'll see that even you won't be able to tell which method would be called without the explicit cast – Panagiotis Kanavos Mar 11 '20 at 13:45
  • Ok you can post answer , i will accept it. – Bercovici Adrian Mar 11 '20 at 13:46

0 Answers0