In C#, when should you use interfaces and when should you use abstract classes? What can be the deciding factor?
The short answer: An abstract class allows you to create functionality that subclasses can implement or override. An interface only allows you to define functionality, not implement it. And whereas a class can extend only one abstract class, it can take advantage of multiple interfaces.
Abstract Class. An abstract class permits you to make functionality that subclasses can implement or override whereas an interface only permits you to state functionality but not to implement it. A class can extend only one abstract class while a class can implement multiple interfaces.
Abstract class can inherit another class using extends keyword and implement an interface. Interface can inherit only an inteface. Abstract class can be inherited using extends keyword. Interface can only be implemented using implements keyword.
Update: C# 8.0 New Feature: Beginning with C# 8.0, an interface may define a default implementation for members, including properties. Defining a default implementation for a property in an interface is rare because interfaces may not define instance data fields.
The advantages of an abstract class are:
Interfaces are merely data passing contracts and do not have these features. However, they are typically more flexible as a type can only be derived from one class, but can implement any number of interfaces.
Abstract classes and interfaces are semantically different, although their usage can overlap.
An abstract class is generally used as a building basis for similar classes. Implementation that is common for the classes can be in the abstract class.
An interface is generally used to specify an ability for classes, where the classes doesn't have to be very similar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With