Sidney
Sidney

Reputation: 708

C# default interface implementation transitivity -- why am I getting this error?

I have come across a scenario where I want to use a default interface implementation in .NET 8.0 that I am having trouble with. In the simple example shown below, my compiler is complaining that Baz does not implement IFoo.Foo(string), but I'm thinking that since IBar does provide a default implementation of Foo, anything that inherits from IBar should already implement Foo.

A screenshot of the C# code from Visual Studio showing error indicators and one error text:

An image of c# code from visual studio showing error indicators and one error text

I did notice that IBar's implementation of Foo does have a warning squiggle suggesting that I might need a new keyword, I tried that and it resolves the warning squiggle there, but the Baz class still has an error as it doesn't implement IFoo.Foo

The other error indicator that is not shown in the first screenshot:

The other error indicator that is not shown in the first picture

Am I missing something here? Is this a known limitation? Have I discovered a bug in the implementation?

Upvotes: 0

Views: 67

Answers (1)

Ivan Petrov
Ivan Petrov

Reputation: 4445

You need to do explicit interface implementation syntax:

interface IBar : IFoo 
{
    void IFoo.Foo(string foo) => Console.WriteLine("foo");
}

You can check the part from the default interface methods docs about Explicit implementation in interfaces:

An implementation declaration is permitted to explicitly implement a particular base interface method by qualifying the declaration with the interface name (no access modifier is permitted in this case). Implicit implementations are not permitted.

You were trying to do "implicit implementation" - which is how interfaces are normally implemented in classes - just using the same method signature. But you are in interface "hierarchy" land, so the language designers have decided to introduce a special syntax similar to how you use override to provide implementation for virtual methods in class hierarchy.

Upvotes: 1

Related Questions