When to use interface and when to use abstraction in C#
When designing applications, it is important to know when to use an abstract class and when to use an interface. Although abstract classes and interfaces seem similar in some ways, there are key differences that will determine which is the best choice for what you’re trying to accomplish.
An abstract class allows you to create functionality that sub-classes 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.
C# abstract class explained
A method without implementation or body is known as an abstract method. These methods contain only declaration of the method.To declare an abstract method, we have to use abstract modifier on the method. When the abstract class inherits the derived class, the derived class must implement the abstract methods using override keyword in it.
C# Interface explained
It is also user defined type like a class which only contains abstract members in it. These abstract members should be given the implementation under a child class of an interface. A class can be inherited from a class or from an interface.
An abstract class can contain an interface plus implementations. This simplifies versioning. An abstract class can be extended by adding new non abstract methods with default implementations. Also, a convenience method is easily added to an abstract class.
An interface cannot be modified without breaking its contract with the classes which implement it. Once an interface has been shipped, its member set is permanently fixed. An API based on interfaces can only be extended by adding new interfaces.
2. Design flexibility
Interfaces offer more design flexibility; precisely because, they can be implemented by any class regardless of its type hierarchy.
When to use an abstract class
- When creating a class library which will be widely distributed or reused to clients, use an abstract class in preference to an interface; because, it simplifies versioning.
- Use an abstract class to provide default behavior
- Use an abstract class to define a common base class for a family of types.
When to use an Interface class
- When creating a standalone project which can be changed at will, use an interface in preference to an abstract class; because, it offers more design flexibility.
- Use an interface to design a polymorphic hierarchy for value types.
- Use an interface when an immutable contract is really intended.
- Use an interface when need to implement multiple inheritance.