Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# default interface implementation - can't override

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?

like image 336
Random Avatar asked May 08 '26 20:05

Random


1 Answers

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"); }
}
like image 182
Random Avatar answered May 11 '26 11:05

Random



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!