What's Coming in C# 8.0? Default Interface Methods

Again, before I go any further, I would like to point out that as I'm writing this, the feature-set for C# 8.0 still hasn't been decided. This means that information written here is subject to change.

One of the new features being proposed in C# 8.0 is to add support for virtual extension methods (methods in interfaces with concrete implementations). Java already has something similar called Default Methods.

Why?

The main reason to introduce Default Interface Methods is to enable developers to add methods to an interface in future versions without breaking source or binary compatibility with existing implementations of that interface. Coincidentally, adding default interface implementations to a language also introduces a new language feature: traits. Traits have proven to be a powerful programming technique.

How?

The simplest way of how to use this feature is by adding a concrete method in an interface, which is a method with a body.

interface IMyInterface
{
    void MyMethod() { Debug.Log("IMyInterface.MyMethod()"); }
}

A class that implements this interface need not implement its concrete method.

class MyClass : IMyInterface {} // This is allowed by the compiler since MyClass implements MyMethod

IMyInterface i = new MyClass();
i.MyMethod(); // prints "IMyInterface.MyMethod()"

As a practical example, let's imagine that we are writing a Wallet Service and we have this interface declaration:

public interface IWallet{
    void PerformTransaction(decimal amount, string description);
}

With the introduction of this feature, we can easily enhance IWallet (even without making any breaking changes) as follows:

public interface IWallet{
    void PerformTransaction(decimal amount, string description);
    void Debit(decimal amount, string description){
        PerformTransaction(amount * -1, description);
    }
    void Credit(decimal amount, string description){
        PerformTransaction(amount, description);
    }
}

Won't Interfaces become Abstract Classes?

In a way yes, but also no. There's no multiple inheritance in languages like C# and Java, which means you can't inherit from more than one class. On the other hand, a class is (and will continue to be) able to implement several interfaces. Another thing which still keeps interfaces unique is Covariance and Contravariance.

Follow Development

If you are interested in participating in discussions about this issue or just want to follow progress, have a look at the proposal on dotnet/csharplang GitHub.