I'm a bit confused about the usage of Abstract classes in C#. In C++, it makes sense to define a template which classes inheriting the abstract class can follow. But, in C# doesn't Interface serve the same purpose?
True that abstract classes can have default implementation which is not provided by Interfaces. So if implementation doesn't need to be included in base class, is it better to go for Interfaces?
The Abstract class and Interface both are used to have abstraction. An abstract class contains an abstract keyword on the declaration whereas an Interface is a sketch that is used to implement a class.
Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing a common functionality to unrelated classes. Interfaces are a good choice when we think that the API will not change for a while.
Abstract class and interface both can't be instantiated. But there are many differences between abstract class and interface that are given below. 1) Abstract class can have abstract and non-abstract methods. Interface can have only abstract methods.
I still like to provide a default abstract implementation of an interface, assuming it's a substantial interface (and it makes sense). You never know when you might add something to the interface that has an easy default implementation that could be included and given "for free" to anyone who inherits from the abstract base class.
This CodeProject article has a lot of information on the difference between the two including a table comparing and contrasting the features of each.
Interfaces define the contract between classes - the ways classes call each other. A class can implement multiple interfaces, but can only inherit from one abstract class.
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