Default Interface Methods
A default interface method gives a promise a ready-made answer, like a job listing that includes a standard training. Classes can use it as is or replace it with their own.
In this page:
Syntax
interface IInterfaceName
{
void MethodName();
void DefaultMethod() // C# 8+ default implementation
{
MethodName();
}
}
Default Interface Methods
Since C# 8, an interface can provide a default body for a method, which implementing classes inherit automatically unless they choose to override it. This lets you add new members to an existing interface without breaking every class that already implements it.
Default methods are still callable only through the interface type in some scenarios, not through the concrete class directly, depending on how they're invoked.
Note:
Default interface methods are great for adding optional convenience behavior without forcing every implementer to write it.
Example: Default Interface Methods
using System;
interface ILogger
{
void Log(string message);
void LogError(string message)
{
Log("ERROR: " + message);
}
}
class ConsoleLogger : ILogger
{
public void Log(string message)
{
Console.WriteLine(message);
}
}
class Program
{
static void Main(string[] args)
{
ILogger logger = new ConsoleLogger();
logger.Log("starting up");
logger.LogError("something failed");
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting that the default method is only available through the interface type, not the class type.
- Using default interface methods on a target framework that does not support them.
- Overusing default implementations, which turns interfaces into abstract classes.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: