Default interface methods let you add new methods to interfaces with a basic implementation. This helps avoid breaking old code when interfaces change.
0
0
Default interface methods in C Sharp (C#)
Introduction
You want to add a new method to an interface without forcing all classes to update immediately.
You want to provide a common behavior for some methods in an interface.
You want to evolve interfaces in a library without breaking existing implementations.
You want to share code between different classes that implement the same interface.
You want to keep interfaces simple but still provide default functionality.
Syntax
C Sharp (C#)
public interface IExample { void ExistingMethod(); void NewMethod() { // default implementation Console.WriteLine("Default behavior"); } }
Default methods have a body inside the interface.
Classes implementing the interface can override the default method or use it as is.
Examples
This interface has a default method
LogWarning that prints a warning message.C Sharp (C#)
public interface ILogger { void Log(string message); void LogWarning(string message) { Console.WriteLine("Warning: " + message); } }
The class implements
ILogger and uses the default LogWarning method without overriding it.C Sharp (C#)
public class ConsoleLogger : ILogger { public void Log(string message) { Console.WriteLine("Log: " + message); } // Uses default LogWarning method }
This class overrides the default
LogWarning method with its own version.C Sharp (C#)
public class CustomLogger : ILogger { public void Log(string message) { Console.WriteLine("Log: " + message); } public void LogWarning(string message) { Console.WriteLine("Custom Warning: " + message); } }
Sample Program
This program shows two classes implementing an interface with a default method. One class uses the default method, the other overrides it.
C Sharp (C#)
using System; public interface IGreet { void SayHello(); void SayGoodbye() { Console.WriteLine("Goodbye from default method!"); } } public class Person : IGreet { public void SayHello() { Console.WriteLine("Hello from Person!"); } // Uses default SayGoodbye method } public class FriendlyPerson : IGreet { public void SayHello() { Console.WriteLine("Hello from FriendlyPerson!"); } public void SayGoodbye() { Console.WriteLine("Goodbye from FriendlyPerson override!"); } } class Program { static void Main() { IGreet p1 = new Person(); IGreet p2 = new FriendlyPerson(); p1.SayHello(); p1.SayGoodbye(); p2.SayHello(); p2.SayGoodbye(); } }
OutputSuccess
Important Notes
Default interface methods were introduced in C# 8.0.
They help keep interfaces flexible and backward compatible.
Use default methods carefully to avoid confusing implementations.
Summary
Default interface methods let interfaces have method bodies.
Classes can use or override these default methods.
This feature helps add new methods without breaking old code.