1

If I have an interface IExampleInterface:

interface IExampleInterface {
    int GetValue();
}

Is there a way to provide a default implementation for GetValue() in a child interface? I.e.:

interface IExampleInterfaceChild : IExampleInterface {
    // Compiler warns that we're just name hiding here. 
    // Attempting to use 'override' keyword results in compiler error.
    int GetValue() => 123; 
}
Xenoprimate
  • 7,691
  • 15
  • 58
  • 95
  • Interfaces do not contain any code. – TaW Jan 17 '21 at 13:54
  • 2
    @TaW they do in the newest version of c#. many think that was a bad design choice, but that's a matter of opinion. @Xenoprimate did you try `new int GetValue() => 123;`? – Franz Gleichmann Jan 17 '21 at 13:55
  • 1
    Hm, interesting, although quite counter-intuitive. But things tend to grow on one.. ;-) – TaW Jan 17 '21 at 13:56

2 Answers2

4

After more experimentation, I found the following solution:

interface IExampleInterfaceChild : IExampleInterface {
    int IExampleInterface.GetValue() => 123; 
}

Using the name of the interface whose method it is that you're providing an implementation for is the right answer (i.e. IParentInterface.ParentMethodName() => ...).

I tested the runtime result using the following code:

class ExampleClass : IExampleInterfaceChild {
        
}

class Program {
    static void Main() {
        IExampleInterface e = new ExampleClass();

        Console.WriteLine(e.GetValue()); // Prints '123'
    }
}
Xenoprimate
  • 7,691
  • 15
  • 58
  • 95
0

In C# 8.0+ the interfaces can have a default method:

https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#default-interface-methods

Otherwise if you are using lower version on C# due to using .Net Framework, you may use an abstract class. but If you want your classes to be able to implement several interfaces, this option may not work for you:

public abstract class ExampleInterfaceChild : IExampleInterface {
    int GetValue() => 123; 
}
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171