What is the difference between an interface with default implementation and abstract class? [duplicate]
Asked Answered
E

1

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?

Exocrine answered 26/9, 2019 at 11:46 Comment(3)
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.Pantelegraph
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, a way to offer reusable code to implementing classes,Maletta
@Pantelegraph you can implement multiple interfaces even if they have conflicting default implementations.Oesophagus
B
11

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.

Battle answered 26/9, 2019 at 11:54 Comment(4)
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 classesMaletta
If you test the code in Sharplab.io you'll the interfaces are identical except for WarnMaletta
@PanagiotisKanavos what does DIM stand for?Roundup
@DavidKlempfner Default Inteface Method, introduced in C# 8.0.Fulvi

© 2022 - 2024 — McMap. All rights reserved.