15

C# 8.0 has introduced a new language feature – default implementations of interface members.

public interface IRobot
{
    void Talk(string message)
    {
        Debug.WriteLine(message);
    }
}

The new default interface implementations provides the elements of the traits language. However is is also blurring the line between what is an abstract class and what is an interface.

What is now the benefit of using an abstract class instead of an interface with default implemenation?

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Postlagerkarte
  • 6,600
  • 5
  • 33
  • 52
  • 5
    You can only inherit from one abstract class but you can implement multiple interfaces (as long as they don't have conflicting default implementations). An abstract class can also have state (fields) that you initialize. – juharr Sep 26 '19 at 11:48
  • They have little in common. DIMs don't specify any kind of inheritance relation while abstract classes do. DIMs are used to implement interface versioning and [traits](https://en.wikipedia.org/wiki/Trait_(computer_programming)), a way to *offer* reusable code to implementing classes, – Panagiotis Kanavos Sep 26 '19 at 13:06
  • 1
    @juharr you can implement multiple interfaces even if they have conflicting default implementations. – Daniel B Oct 27 '21 at 05:04

1 Answers1

10

Funny enough, but the CLR implements default interfaces as abstract classes. CLR supports multiple inheritance. Here is a good article about this.

In C#, you need default interfaces when you need to implement (in this case actually inherit from) multiple interfaces, because the language doesn't let you inherit from multiple classes.

An abstract class also allows you to have state. State, i.e. fields, are not allowed in interfaces.

Nick
  • 4,787
  • 2
  • 18
  • 24
  • That's *not* what this article shows. It shows the method signatures, not the interface implementations themselves. DIMs are supported by the runtime itself, not implemented through abstract classes – Panagiotis Kanavos Sep 26 '19 at 13:19
  • If you test the code in [Sharplab.io](https://sharplab.io/#v2:EYLgtghgzgLgpgJwDQxASwDYB8ACAmARgFgAoHABgAIcCA6AETQgHMA7Ae1jQGMoBuUhUoBlABYQEABwAyEYLQBKAV1Yw0YOAJKCAzJTSrEAMwjc4lAJLT2zZolIBvUpRfUALJdZH2AChpUNKCgWOABKLVd3SgBRBAR2BD8CALggkPDnZ1cAemzKADk4AHdKDRhRdgATLJccDwB1CVYklLS7UJrKJxJIyPo4YCVmWnqENHhpAzgfQOD2iNcAX1Jl7TI9A3gEEzNLa1tEAGEMaCgeR066z28W0tS5sIXaj1j4xP87tsfLhqbb2fSWlWumoeEoh3YrCg7AwcH2dgQlBAexsCIuPVcOD0V1eCX+93SnW6vUxBAAnDMCfNOqtKJdsR4LF5fB8Ae0iZ1IjQKWzvhiXKtFkA==) you'll the interfaces are identical except for `Warn` – Panagiotis Kanavos Sep 26 '19 at 13:19
  • @PanagiotisKanavos what does DIM stand for? – David Klempfner Apr 18 '21 at 11:47
  • @DavidKlempfner *Default Inteface Method*, introduced in C# 8.0. – silkfire Nov 28 '22 at 13:55