Default Interface Method in C#: What It Is and How It Works
default interface method in C# is a method with an implementation inside an interface, allowing interfaces to provide behavior directly. This feature lets you add new methods to interfaces without breaking existing code that implements them.How It Works
Normally, interfaces in C# only declare methods without any implementation, like a contract that classes must follow. With default interface methods, interfaces can now include actual code inside methods. This means the interface can provide a default behavior that implementing classes can use or override.
Think of it like a recipe book (interface) that not only lists the recipe names (method signatures) but also includes a basic recipe (method implementation). If a cook (class) wants, they can follow the recipe exactly or change it to their taste.
This feature helps when you want to add new methods to an interface without forcing all existing classes to implement those new methods immediately, making your code easier to maintain and evolve.
Example
This example shows an interface with a default method and a class that uses it without implementing the method explicitly.
using System;
interface IGreeter
{
void SayHello();
// Default interface method with implementation
void SayGoodbye()
{
Console.WriteLine("Goodbye from default method!");
}
}
class Person : IGreeter
{
public void SayHello()
{
Console.WriteLine("Hello from Person!");
}
}
class Program
{
static void Main()
{
Person p = new Person();
p.SayHello(); // Calls implemented method
((IGreeter)p).SayGoodbye(); // Calls default interface method
}
}When to Use
Use default interface methods when you want to add new functionality to interfaces without breaking existing implementations. This is especially useful in large projects or libraries where many classes implement the same interface.
For example, if you maintain a library and want to add a new method to an interface, default methods let you provide a default behavior so older classes don’t have to change immediately. It also helps to share common code among implementations without forcing inheritance.
Key Points
- Default interface methods allow interfaces to have method implementations.
- They enable adding new methods to interfaces without breaking existing code.
- Implementing classes can override default methods if needed.
- This feature was introduced in C# 8.0 and requires .NET Core 3.0 or later.