Default Interface Methods (DIM) & Non-Breaking API Evolution
1Concept
Default Interface Methods (DIM) allow interface authors to add new methods with default implementations without breaking existing third-party implementations.
2Architecture Diagram
[ ILogger Interface ]
├── void Log(string msg) ── [Abstract]
└── void LogError(string err) => Log("[ERROR] " + err) ── [Default Implementation]
│
▼
[ LegacyLogger ] ── Implements Log(); inherits LogError() automatically!3Code Example
C# 13 & .NET 9
using System;
public interface IMetricsCollector
{
void Record(string metricName, double value);
// Default Interface Method (DIM)
void RecordLatency(string operation, double milliseconds)
{
Record($"latency.{operation}", milliseconds);
}
}
public class SimpleCollector : IMetricsCollector
{
public void Record(string metricName, double value)
{
Console.WriteLine($"Metric: {metricName} = {value}");
}
}
public class DimDemo
{
public static void Main()
{
IMetricsCollector collector = new SimpleCollector();
collector.RecordLatency("CheckoutApi", 12.45);
}
}4Expected Output
Metric: latency.CheckoutApi = 12.45
5Key Takeaways
- ✓DIM provides trait-like capabilities to C# interfaces.
- ✓Default methods are only accessible via the interface reference variable (`IMetricsCollector c = ...`).
- ✓Does not create multiple inheritance diamond state issues because interfaces have no instance fields.