In my project I’ve found a strange situation which seems completely valid in C#, because I have no compilte-time errors.
Simplified example looks like that:
using System;
using System.Collections.Generic;
namespace Test
{
interface IFoo
{
void FooMethod();
}
class A
{
public void FooMethod()
{
Console.WriteLine("implementation");
}
}
class B : A, IFoo
{
}
class Program
{
static void Main(string[] args)
{
IFoo foo = new B();
foo.FooMethod();
}
}
}
Such code compiles. However, note that A is not IFoo and B doesn’t implement IFoo methods. In my case, by accident (after refactoring), A has the method with the same signature. But why should A know how to implement the FooMethod of the IFoo interface? A even doesn’t know that IFoo exist.
For me having such design is dangerous. Because every time I implement some interface I should check if each method in this interface “interferes” with the base class methods.
If this is “pure C# feature”? What is it called? Am I missing something?
For each member in the interface, the compiler simply looks for an explicit implementation (if one), then a public implementation (implicit implementation), i.e. a method on the public API that matches the interface signature. In this case,
A.FooMethod()looks like a fine match for a public implementation. IfBwasn’t happy with that selection, it could eithernewthe method, or use an explicit implementation; the latter would be preferred: