C# 8.0 New Feature–Interface Default Implementation for Methods

On this page

C# 8.0 brings a change to something that has been fixed since the first version of the language: an interface can now give a method a body. A class that implements the interface and says nothing about that method gets the body from the interface. A class that wants its own version writes one, as before.

Until now every member of an interface had to be implemented by every class that implemented it. This post shows how to try the new behaviour with the first previews, what the rules are when you call such a method, and where it is useful.

The problem

An interface is a promise, and once other people have written classes against it the promise is hard to change. Add one method to a published interface and every implementing class stops compiling until somebody adds that method. For a library with users you have never met, that is a breaking change.

The usual ways around it all cost something. An abstract base class can carry shared code, but a class has only one base class. Extension methods can add behaviour, but an implementer cannot replace them with something better. A second interface, the familiar IThing2, works and leaves the mess in the type names for good.

A default implementation answers this directly. The new method arrives with a body, existing implementers keep compiling, and any class that can do better overrides it.

When will we get C# 8.0?

C# 8.0 is planned to ship along with .NET Core 3.0. Preview 1 of both .NET Core 3.0 and Visual Studio 2019 is available to try now.

One thing is different about this feature. Most language features are the compiler’s work alone and run on any runtime. A method body in an interface needs the runtime to cooperate, so it depends on the platform. Microsoft has said that C# 8.0 will be supported on platforms that implement .NET Standard 2.1, that .NET Core 3.0 will be one of them, and that .NET Framework 4.8 will not. If your code has to run on .NET Framework, this feature is not coming to it.

Setup

1. Download and install Preview 1 of .NET Core 3.0 and Preview 1 of Visual Studio 2019.

Installing the .NET Core 3.0 and Visual Studio 2019 previews, screenshot 1 of 3
Installing the .NET Core 3.0 and Visual Studio 2019 previews, screenshot 2 of 3
Installing the .NET Core 3.0 and Visual Studio 2019 previews, screenshot 3 of 3

2. Start Visual Studio 2019 Preview, create a new project and choose “Console App (.NET Core)” as the project type.

Creating a Console App (.NET Core) project in Visual Studio 2019 Preview, screenshot 1 of 3
Creating a Console App (.NET Core) project in Visual Studio 2019 Preview, screenshot 2 of 3
Creating a Console App (.NET Core) project in Visual Studio 2019 Preview, screenshot 3 of 3

3. When the project is open, change its target framework to .NET Core 3.0. Right-click the project in Solution Explorer, choose Properties, and use the drop-down on the Application tab.

Project properties in Visual Studio 2019 Preview with the target framework set to .NET Core 3.0

The project also has to compile as C# 8.0. If the compiler is on an older language version it refuses the method body with this error:

Text1 line
error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater.

Setting <LangVersion>8.0</LangVersion> in the project file fixes that.

The example

The interface below has two methods. DisplayMessage has no body, so every class must implement it. DefaultMessage has one. Bmw leaves it alone. Audi supplies its own.

C#45 lines
using System;

namespace CSharp8Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            IVehicle bmw = new Bmw();
            bmw.DisplayMessage();
            bmw.DefaultMessage();

            IVehicle audi = new Audi();
            audi.DisplayMessage();
            audi.DefaultMessage();
        }
    }

    interface IVehicle
    {
        // No body: every implementing class must provide this one.
        void DisplayMessage();

        // A body: classes that say nothing about this method get this implementation.
        void DefaultMessage() { Console.WriteLine("I am inside the default method in the interface!"); }
    }

    public class Bmw : IVehicle
    {
        public void DisplayMessage()
        {
            Console.WriteLine("I am BMW!!!");
        }
    }

    public class Audi : IVehicle
    {
        public void DisplayMessage()
        {
            Console.WriteLine("I am AUDI!!!");
        }

        public void DefaultMessage() => Console.WriteLine("I am inside the Audi class!");
    }
}

This is what it prints:

Text4 lines
I am BMW!!!
I am inside the default method in the interface!
I am AUDI!!!
I am inside the Audi class!

The BMW gets the interface’s body. The Audi gets its own, even though the variable is typed as IVehicle: the call goes to the most specific implementation the object has.

Calling a default method

There is one rule that surprises people. Notice that the example declares its variables as IVehicle, not as Bmw. That is not style. A default method belongs to the interface, and a class that does not implement it does not have it as a member. This does not compile:

C#10 lines
class Bmw : IVehicle { }

class Program
{
    static void Main()
    {
        Bmw bmw = new Bmw();
        bmw.DefaultMessage();   // the variable is a Bmw, and Bmw has no such member
    }
}
Text1 line
error CS1061: 'Bmw' does not contain a definition for 'DefaultMessage' and no accessible extension method 'DefaultMessage' accepting a first argument of type 'Bmw' could be found (are you missing a using directive or an assembly reference?)

Assign the object to an IVehicle variable, or cast it, and the call works. In practice this matters less than it sounds, because code that depends on an interface usually holds the interface type anyway. It does mean a default method is not a way to give a class new public members.

Adding a method to a published interface

This is the case the feature was designed for. An interface already has implementers, and a later version needs one more method. ConsoleLogger below was written against the first version and has not been touched. TaggedLogger was written later and has its own way to report an error.

C#22 lines
    // Version 2 of an interface that other teams already implement.
    // LogError is new. It has a body, so version 1 implementers keep compiling.
    public interface ILogger
    {
        void Log(string message);

        void LogError(Exception error) => Log("ERROR " + error.GetType().Name + ": " + error.Message);
    }

    // Written against version 1. Not touched since.
    public class ConsoleLogger : ILogger
    {
        public void Log(string message) => Console.WriteLine(message);
    }

    // Written against version 2, with its own idea of how to report an error.
    public class TaggedLogger : ILogger
    {
        public void Log(string message) => Console.WriteLine("[app] " + message);

        public void LogError(Exception error) => Console.WriteLine("[app] !! " + error.Message);
    }
Text4 lines
starting
ERROR InvalidOperationException: the order was already shipped
[app] starting
[app] !! the order was already shipped

The old class reports the error through the default body, which is written in terms of the one method the old class does have. That is the pattern to copy: a default implementation should be built from the interface’s other members, because those are all it can rely on. An interface still has no instance fields, so a default method cannot keep state of its own.

When two defaults collide

A class can implement many interfaces, so two of them can disagree. Here IElectric and ILuxury both replace the default that IVehicle provides, and Car implements both without choosing.

C#5 lines
interface IVehicle { void Describe() { Console.WriteLine("a vehicle"); } }
interface IElectric : IVehicle { void IVehicle.Describe() { Console.WriteLine("an electric vehicle"); } }
interface ILuxury : IVehicle { void IVehicle.Describe() { Console.WriteLine("a luxury vehicle"); } }

class Car : IElectric, ILuxury { }   // which Describe does a Car get?

The compiler does not guess. It stops:

Text1 line
error CS8705: Interface member 'IVehicle.Describe()' does not have a most specific implementation. Neither 'IElectric.IVehicle.Describe()', nor 'ILuxury.IVehicle.Describe()' are most specific.

The fix is for the class to say what it wants. With a Describe method on Car, the program compiles, and each object gets the most specific body available to it:

C#6 lines
class Bike : IVehicle { }
class Leaf : IElectric { }
class Car : IElectric, ILuxury
{
    public void Describe() { Console.WriteLine("an electric luxury car"); }   // the class settles it
}
Text3 lines
a vehicle
an electric vehicle
an electric luxury car
%%{init: {'theme':'base','themeVariables':{'primaryColor':'#FFF3E0','primaryTextColor':'#232F3E','primaryBorderColor':'#FF9900','lineColor':'#232F3E','clusterBkg':'#F8FAFC','clusterBorder':'#CBD5E1','edgeLabelBackground':'#FFFFFF','nodeTextColor':'#232F3E'}}}%%
flowchart TD
    A["A call through the interface type"] --> B{"Does the class implement the method?"}
    B -- Yes --> C["The class's method runs"]
    B -- No --> D{"Does one interface give the most specific body?"}
    D -- Yes --> E["That interface's body runs"]
    D -- "No, two disagree" --> F["Compile error CS8705:
the class must choose"] style C fill:#F0FFF4,stroke:#1D8102,stroke-width:2px,color:#145202 style E fill:#F0FFF4,stroke:#1D8102,stroke-width:2px,color:#145202 style F fill:#FEF2F2,stroke:#D13212,stroke-width:2px,color:#991B1B

When to use it

SituationUse a default implementation?Why
Adding a member to an interface others already implementYesExisting classes keep compiling, new ones can override
A convenience method built from the interface’s other membersYesOne place for the logic, and implementers can still do better
Shared behaviour that needs fieldsNo, use an abstract base classAn interface has no instance state
Giving classes new public membersNoThe method is reachable only through the interface type
Code that must run on .NET FrameworkNoThe runtime support is not planned there

Used with restraint this makes interfaces easier to live with over years. Used freely it turns an interface into a base class with worse tooling. My own rule will be to reach for it when an interface has to grow, and not when a new one is being designed.

Key takeaways

  • In C# 8.0 an interface method can have a body. Classes that do not implement the method get that body.
  • A class’s own implementation always wins over the interface’s.
  • A default method is called through the interface type. Calling it on a variable of the class type is compile error CS1061.
  • If two interfaces supply competing bodies, the compiler reports CS8705 and the class has to implement the method itself.
  • The feature needs runtime support: .NET Core 3.0, and not .NET Framework 4.8.
  • Its best use is adding a member to an interface that already has implementers.
📝
HOW THIS WAS CHECKED

Every listing in this post was compiled with the language version set to 8.0 and run, and the outputs and compiler errors are copied from that run: GitHub Actions run 44552918548, commit ccbb0d9. Three of the six projects are expected not to compile, and the run checks that each fails with exactly the error shown. The screenshots are from my own installation of the previews and that installation was not repeated for the run. The statement about .NET Framework 4.8 is from Microsoft’s “Building C# 8.0” post and was not tested here.

References & Further Reading


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Written by

Nithin Mohan TK

Hello Namaste! 👋🏻 I'm an accomplished Enterprise Solution Architect & Engineering Leader with 20+ years of progressive experience architecting, building, and scaling transformative enterprise solutions. ⚜️ Solution Architect / AI & Cloud 📌 Galway, Ireland

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.