Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we replace abstract class with Interface with Default Methods in C#

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?

like image 284
Jaganmohanreddy Avatar asked Oct 24 '25 16:10

Jaganmohanreddy


1 Answers

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.

like image 128
Jon Skeet Avatar answered Oct 27 '25 10:10

Jon Skeet