4

In C# 8.0 we have a new feature where we can provide a default method implementation in Interfaces which can also be overridden by its implementing classes as well.

We used to have Abstract classes with instance methods to provide a common functionality for all of its implementing classes.

Now can I replace those Abstract classes who are having Instance methods with Interfaces who are having Default method implementations from C# 8.0 on wards?

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Jaganmohanreddy
  • 391
  • 4
  • 19
  • It would be awesome if you could provide a [mcve] – jazb Dec 12 '19 at 07:06
  • Replace them in which cases? Interfaces are still interfaces, even if they can have code. They can't hold state, handle events or create an inheritance relation. If you have method-only abstract classes that *don't* introduce an `is-a` relation, then *maybe* you can use DIMs. Post your code – Panagiotis Kanavos Dec 12 '19 at 08:22

2 Answers2

5

No, abstract classes still have their place. In particular, abstract classes can declare fields (often via automatically implemented properties these days), which interfaces still can't. They can also define constructors, and perform validation in them.

Here's an example of something you couldn't do with an interface:

public abstract class NamedObject
{
    public string Name { get; }

    protected NamedObject(string name) =>
        Name = name ?? throw new ArgumentNullException(nameof(name));

    // Abstract methods here
}

Obviously it wouldn't really be called NamedObject - there'd be a business-specific reason for it to be abstract, which would determine the name. But the behaviour here is behaviour that can't be put in an interface.

zastrowm
  • 8,017
  • 3
  • 43
  • 63
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Events are another problem because they're backed by delegate fields. Creating a trait for `INotifyPropertyChanged` would be very useful but there's no way (that I know of) to implement the event – Panagiotis Kanavos Dec 12 '19 at 08:20
0

You can in most cases but probably you shouldn't. The default functionality in the interfaces is there to solve another problem.

It's there for when you can't change an existing class, if for example is in some other project/ibrary and you want to extend the functionality without changing all the code with an abstract class..

Maybe it does make sense to have as an Abstract class? An object that has behavior but does not make sense on its own and must be extended should be better modeled by a class. If you have the Car class with behavior, then you can have the length private member which applied to all cars. Private members are not part of the interfaces.

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61