Reputation: 431
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?
Upvotes: 4
Views: 1459
Reputation: 1500335
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.
Upvotes: 5
Reputation: 26362
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.
Upvotes: 0