C# 8.0 Interface default implementation
In the upcoming C# 8.0, interface can have default implementation of members. The class implementing interface can provide its own implementation otherwise the default implementation from the interface is used.
This feature allows to safely add members to an interface already released while existing client can continue to work without any change.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public interface IPaymentMethod { void CreditCard(); void DebitCard(); void BitCoin(); // newly added } public class PaymentMethod : IPaymentMethod { public void CreditCard() { Console.WriteLine("Process credit card"); } public void DebitCard() { Console.WriteLine("Process debit card"); } } |
Above code gives error during compilation:
1 2 | PaymentMethod' does not implement interface member 'IPaymentMethod.BitCoin()' |
Now let’s add default implementation to the interface so that existing client can continue to work without change.
1 2 3 4 5 6 7 8 9 | public interface IPaymentMethod { void CreditCard(); void DebitCard(); void BitCoin() { Console.WriteLine("Process bitcoin (default)"); } } |
Final words:
A class implementation of an interface member should always win over a default implementation in an interface, even if it is inherited from a base class.
Default implementation in an interface are fall back only when the class does not have any implementation of the member at all.