📎 Webclip
Default Interface Implementations in C#: Where Inheritance Goes to Troll You
Default interface implementations in C# let interfaces ship methods with default bodies, which helps API evolution but can hide tricky behavior when inheritance enters the picture. The article shows a service that returns the interface default after a base class is added, even though the concrete class still defines the method.
Fichamento #
- Default interface implementations were introduced in C# 8.0 and let interfaces define methods with default bodies.
- The feature helps add methods without breaking existing implementations and improves interoperation with platforms like Android and iOS.
- The article focuses on a case where this behavior becomes subtle when combined with inheritance and dependency injection.
- A service named
MyServicereceives anIFooand callsGetValue()to print the result. IFooprovides a defaultGetValue()that returns"IFoo".Foodefines its ownGetValue()that returns"Foo", and a unit test againstFoopasses.- The console app also prints
"Foo"before any refactor. - After introducing
FooBase : IFooand makingFooinherit from it, the tests still pass but the program output changes to"IFoo". - The explanation given is that the CLR builds a method table for type resolution and follows the inheritance chain when resolving interface calls.
- Once
Foono longer directly implementsIFoo, the runtime looks toFooBase, finds noGetValue()there, and falls back to the interface default implementation. - The article recommends understanding how default methods behave with inheritance and avoiding unnecessary inheritance.
- It suggests preferring composition over inheritance when shared logic is needed.
- It also recommends explicitly declaring the interface on derived classes and providing overrides when needed.
- The article advises testing through the interface instead of relying on a concrete class or
var. - It mentions static analysis tools such as Roslyn analyzers and SonarAnalyzer for .NET.
- It ends by recommending documentation and careful review for changes involving default methods.