C# Version 8.0

https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8

Overview

Default Interface Methods

Whaaat, interfaces with implemented methods? Don’t they mean abstract classes? How could this work? That were my first thoughts, but believe me, this is super cool innovation.

Let’s assume you have an interface and there are a huge number of implementations of that interface. Some implementations are controlled by you, but most aren’t. Everything with that interface looks fine, naming is perfect, properties and methods are complete, everything looks good. Then, one day, someone has the idea to add a method to the interface and you have to admit, the idea is really, really good. But how to do that? Simply adding the method to the interface would result in a breaking change, all implementations would have to be changed! Defining a new Interface wouldn’t be much better.

Expanding the interface by that method with a default implementation is a real smart solution. No one has to touch any implementation and everyone can use the new method. If that default implementation isn’t sufficient you can change it by implementing the new method in your class.

interface IDefaultInterfaceMethods
{
    void DoSomething();
    int LaterAddedCoolMethod(int a, int b)
    {
        var result = a + b;
        return result;
    }
}
class MyImplementation : IDefaultInterfaceMethods
{
    //no changes necessary here
}
class UsageOfDefaultImplementation
{
    void UseIt()
    {
        IDefaultInterfaceMethods myImpl = new MyImplementation ();
        var sum = myImpl.LaterAddedCoolMethod(3, 4);
    }
}

Isn’t that cool? You can simply use the new method LaterAddedCoolMethod without changing your implementation. You only have to watch out not to use your implementing class directly. Instead program against the interface and make use of dependency injection. But that’s what anyone would do, isn’t it?

#