With the recent release of C# 8.0 (new feature mentioned here), it allows for providing default method implementation.
While I understand the reason why it's done, I wonder if there is any difference between these 2 concepts?
Thoughts?
With the recent release of C# 8.0 (new feature mentioned here), it allows for providing default method implementation.
While I understand the reason why it's done, I wonder if there is any difference between these 2 concepts?
Thoughts?
It is better to use abstract class for base functionality (provides better inheritance tree logic). And use interfaces with default method implementations to provide small side changes only when this default logic suits for most of implementations (like Microsoft did with their Collection methods).
Also try to not overuse default interface implementations, because this complicates behavior inheritance (you need to search interfaces too, not only classes) from linear to tree.
C++ allows multiple inheritance and without control this aspect can easily make the code unmaintainable.
These are the main differences I see:
Unlike other languages (like C++), C# does not allow a class to inherit directly from more that one class. On the other hand, a class can implement any number of interfaces, so the new default implementation feature allows you to do something similar to multi-inheritance.
If you derive from a class and override a virtual method, you may use the base
keyword to call the original implementation. Example:
public abstract class Base
{
public virtual void DoSomething()
{
...
}
}
public class Derived : Base
{
public override void DoSomething()
{
base.DoSomething(); //Here
...
}
}
Abstract classes can declare constructors that the derived class will call. Also, an abstract class can contain non-virtual methods, while an interface can only have overridable (virtual) methods.