Default Interface Methods
In this page:
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
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: