How do I provide a default implementation in a child interface?

560 Views Asked by At

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; 
}
2

There are 2 best solutions below

0
Xenoprimate On BEST ANSWER

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'
    }
}
2
Ashkan Mobayen Khiabani On

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; 
}