C# default interface implementation - can't override

4.3k views Asked by At

I'm following this guide https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods to use default interface implementation feature. I've copied a code that defines a default implementation in interface IA and then overrides it in interface IB:

interface I0
{
    void M() { Console.WriteLine("I0"); }
}

interface I1 : I0
{
    override void M() { Console.WriteLine("I1"); }
}

But it gives be an error CS0106 The modifier 'override' is not valid for this item and a warning CS0108 'I1.M()' hides inherited member 'I0.M()'. Use the new keyword if hiding was intended. TargetFramework is set to net5.0, LangVersion is latest. Why it's not working even if it's described in official docs?

2

There are 2 answers

0
Random On BEST ANSWER

Apparently, examples with override keyword are incorrect, this keyword must be removed. Also, it's only working if method interface is specified explicitly:

interface I0
{
    void M() { Console.WriteLine("I0"); }
}

interface I1 : I0
{
    void I0.M() { Console.WriteLine("I1"); }
}
1
Peter B On

In the text it says "Implicit overrides are not permitted."

Confusingly the IC interface that follows it does not repeat that statement, while using the implicit approach, making it look like the implicit approach is valid. And IC seems to be the interface that you copied from.