interface methods

C# 8 default interface methods

C# 8 default interface methods

In the previous articles, we discussed C# 8 async streams and pattern matching. In this article, we’ll look at C# 8 default interface methods.

Extending interfaces

Before C# 8, it was not possible to add members to an interface without breaking the classes that implement the interface. Because interface members were abstract, classes needed to provide an implementation. C# 8 allows us to extend an interface and provide a default implementation. The runtime (which also needs to support this feature) uses the default implementation when the class does not provide it:

interface IOutput
{
    void PrintMessage(string message);
    void PrintException(Exception exception)
        => PrintMessage($"Exception: {exception}");
}
class ConsoleOutput : IOutput
{
    public void PrintMessage(string message)
        => Console.WriteLine(message);
}

In this example, ConsoleOutput does not provide an implementation for PrintException. When PrintException is called against a ConsoleOutput instance, the default method from the IOutput interface will be called. ConsoleOutput might provide its own implementation.

Continue reading “C# 8 default interface methods”

Share