Junior — Middle
Is it possible to declare the implementation of a method directly in the interface definition?
sobes.tech AI
Answer from AI
Starting from C# 8.0, interfaces gained the ability to declare method implementations directly within their definitions — this is called "default interface methods." This allows adding new methods to interfaces without breaking existing implementations.
Example:
public interface ILogger
{
void Log(string message); // regular interface method
void LogWarning(string message) // default implementation method
{
Log("Warning: " + message);
}
}
Previously, interfaces could only declare method signatures without bodies. Now, methods can have bodies, expanding the capabilities of interfaces.