Search code examples
c#c#-8.0default-interface-member

How to call default implementation of overridden interface method in C# 8.0?


I'm starting to use C# 8.0 and default interface implementations. According to the official C# documentation, we can call the default implementation of an interface method from another object derived from it using the syntax IBaseInterface.base.Method(), as shown in this code snippet from the official documentation

interface I0
{
   void M() { Console.WriteLine("I0"); }
}
interface I1 : I0
{
   override void M() { Console.WriteLine("I1"); }
}
interface I2 : I0
{
   override void M() { Console.WriteLine("I2"); }
}
interface I3 : I1, I2
{
   // an explicit override that invoke's a base interface's default method
   void I0.M() { I2.base.M(); }
}

However, the syntax I2.base.M() gives an error. Can anyone confirm if there's an error in the documentation? Also, the override keyword cannot be used in the definition of an interface method, and I can't find any additional information on the topic.

If this code is invalid, does C# have a way to execute { Console.WriteLine("I0"); }, i.e., the default implementation of I0.M(), from an instance of the I3 interface?

EDIT: So far, the only way I have been able to do it is by using this tricky code with the static method DefaultM().

interface I0
{
   protected static void DefaultM() { Console.WriteLine("I0"); } 
   void M() { DefaultM(); }
}
interface I1 : I0
{
   void IO.M() { Console.WriteLine("I1"); }
}
interface I2 : I0
{
   void IO.M() { Console.WriteLine("I2"); }
}
interface I3 : I1, I2
{
   // an explicit override that invoke's a base interface's default method
   void I0.M() { I0.DefaultM(); }
}

Solution

  • Can anyone confirm if there's an error in the documentation?

    Kind of. This is actually text from feature proposal (source path: csharplang/proposals/csharp-8.0/default-interface-methods.md) since currently there is no full spec for C# 8+ (as far as I understand draft one for C# 7 is currently worked on).

    From C# LDM for Oct 17, 2018:

    Does an override in an interface introduce a new member?

    No override keyword in interfaces. This should resolve all listed questions.

    From C# LDM for April 29, 2019:

    Conclusion

    Cut base() syntax for C# 8. We intend to bring this back in the next major release.