Junior — Middle
Is it possible to define specific implementations of methods within an interface?
sobes.tech AI
Answer from AI
In C# starting from version 8.0, it became possible to define method implementations within an interface — these are called default interface methods.
This allows adding new methods to interfaces without breaking existing implementations.
Example:
public interface ILogger
{
void Log(string message);
void LogError(string message) // default interface method
{
Log("ERROR: " + message);
}
}
public class ConsoleLogger : ILogger
{
public void Log(string message)
{
Console.WriteLine(message);
}
}
Thus, the ConsoleLogger class may not implement LogError, and it will still work by default.