C# 8 has added support for default interface implementation, meaning that you can define a method body right on the interface which will be used as automatic implementation in any class implementing the interface. There’s however a nasty error that is very easily created and hard to detect when using this new feature. Consider the following:
public class A : IA
{
public void Method(long a) => Console.WriteLine("class");
}
public interface IA
{
void Method(int b) => Console.WriteLine("interface");
}
A myClass = new A();
IA myInterface = myClass;
myClass.Method(1);
myInterface.Method(1);
The output is actually this:
class
interface
The reason is that the class actually haven’t overridden the method, because the method parameters have different types (int vs long). What may look like an implicit interface implementation, is actually a definition of an extra method. Normally you would get an error that the class A
doesn’t implement interface IA
, but since IA
provides a default implementation, class A actually defined a new member with the same. This issue is incredibly easy to create when refactoring code and hard to detect.
Java actually has an answer to this by allowing you to add an annotation @Override
to your methods (annotations in Java are direct equivalent of .NET attributes). This will make compiler throw if that method doesn’t actually implement one of the base class methods or interfaces. Fortunately this something that can be easily fixed with a Roslyn analyzer.
I’ve put together a prototype, which you can preview below. After some cleanup, I’ll publish it on NuGet for easy consumption.