Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If default interface methods are implemented in C# 8.0 why would I ever need abstract classes? [closed]

I recently ran into a list of features that are being considered for addition in the next version of C#. One of them is called "default interface methods":

https://github.com/dotnet/csharplang/blob/master/proposals/default-interface-methods.md

In short, it will allow you to define actual method implementations on the interfaces themselves meaning interfaces can now have implementations. Since this is the case, and C# classes can implement/inherit from multiple interfaces then why in the world would I ever use abstract classes?

The only thing that comes to my mind is that interfaces cannot have a constructor so maybe there is a need to run some logic in the abstract class constructor and that would justify defining an abstract class.

Is there any other scenario that anyone can think of?

like image 978
Marko Avatar asked Aug 11 '17 18:08

Marko


People also ask

What are default interface methods?

Default interface methods enable an API author to add methods to an interface in future versions without breaking source or binary compatibility with existing implementations of that interface. The feature enables C# to interoperate with APIs targeting Android (Java) and iOS (Swift), which support similar features.

Can we override default method of interface C#?

C# default interface implementation - can't override.

CAN interface have default implemented methods?

Interfaces can have default methods with implementation in Java 8 on later. Interfaces can have static methods as well, similar to static methods in classes. Default methods were introduced to provide backward compatibility for old interfaces so that they can have new methods without affecting existing code.

Can default interface methods be overridden?

you can override a default method of an interface from the implementing class.


2 Answers

Apart from state as mentioned in comments,

Base Class

You can't inherit an interface from a Base class. Interface can only inherit an interface. You would need abstract class to derive from some other class. And since you can't inherit from class, you can't override class methods. Which you can override in abstract class.

like image 123
Akash Kava Avatar answered Oct 21 '22 02:10

Akash Kava


Usually class inheritance feels like a taxonomy (x 'is a' y), while interfaces are behaviours (x 'can do' y), so there is a subtle difference in implied meaning. Although you're right that the technical distinction is less clear cut.

like image 35
matt_t_gregg Avatar answered Oct 21 '22 00:10

matt_t_gregg