How do default interface methods (C# 8+) let an interface provide implementation, and what backward-compatibility problem do they solve?
Short answer
A default interface method provides a BODY directly in the interface declaration, so implementing classes AUTOMATICALLY inherit that behavior unless they choose to override it — this specifically solves the problem of adding a NEW method to an existing, widely-implemented…
Advertisement
AModel answer
A default interface method provides a BODY directly in the interface declaration, so implementing classes AUTOMATICALLY inherit that behavior unless they choose to override it — this specifically solves the problem of adding a NEW method to an existing, widely-implemented interface (like adding a method to IEnumerable<T>) without BREAKING every existing implementation that doesn't have it yet.
public interface ILogger {
void Log(string message);
void LogError(string message) => Log($"ERROR: {message}"); // default implementation, C# 8+
}
public class ConsoleLogger : ILogger {
public void Log(string message) => Console.WriteLine(message);
// LogError is inherited automatically -- no need to implement it
}Real-world example
Adding a new convenience method to a widely-used library interface without breaking every existing implementing class.
Likely follow-ups
- Can a class that implements the interface still choose to OVERRIDE a default interface method's implementation?
Related topics