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