Default interface methods were introduced in C# 8.0 to allow interfaces to provide a default implementation for their members. This enables extending interfaces without breaking existing implementations, which was previously not possible since adding a new method to an interface required all implementing classes to define it.
Key Points
- Default Implementation: An interface can include a method with a body using the default implementation.
- Backward Compatibility: Existing classes implementing the interface do not need to implement the new method unless they want to override it.
- Optional Override: Implementing classes can override the default method to provide a custom implementation.
- Access Modifiers: Default interface methods can be public (default), private (for use only inside the interface), protected, internal or protected internal.
Regular Interface Method must be implemented by every class that implements the interface meanwhile Default Interface Method provides a built-in implementation, classes can use it as-is or override it.
Interface with Default Method
Here we define an interface IDevice with one abstract method TurnOn and one default method ShowInfo.
using System;
public interface IDevice
{
void TurnOn(); // Abstract method
void ShowInfo() // Default method
{
Console.WriteLine("This is a device.");
}
}
- TurnOn() must be implemented by any class that implements IDevice.
- ShowInfo() has a default implementation, so classes can use it as-is or override it.
Implementing Classes
We create two classes Phone and Laptop that implement IDevice.
public class Phone : IDevice
{
public void TurnOn()
{
Console.WriteLine("Phone is turning on");
}
// Uses default ShowInfo
}
public class Laptop : IDevice
{
public void TurnOn()
{
Console.WriteLine("Laptop is turning on");
}
public void ShowInfo() // Override default method
{
Console.WriteLine("This is a laptop");
}
}
- Phone does not override ShowInfo, so it uses the interface’s default method.
- Laptop overrides ShowInfo to provide its own implementation.
Usage
We create instances of Phone and Laptop and call their methods.
class Program
{
static void Main()
{
IDevice phone = new Phone();
phone.TurnOn();
phone.ShowInfo();
IDevice laptop = new Laptop();
laptop.TurnOn();
laptop.ShowInfo();
}
}
- phone.TurnOn() calls Phone’s implementation.
- phone.ShowInfo() calls the default interface method.
- laptop.TurnOn() calls Laptop’s implementation.
- laptop.ShowInfo() calls the overridden method in Laptop.
Output
Phone is turning on
This is a device.
Laptop is turning on
This is a laptop