Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading