c# – What is the benefit of an abstract class implementing an interface?


ADO.NET has classes that inherit from abstract classes, and abstract classes, in turn, implement an interface.

For example, there are SqlCommand and OleDbCommand and so on that extend the abstract DbCommand , and DbCommand implements the IDbCommand interface.

In short, everything inherits from the abstract DbCommand .

Why did Microsoft choose this implementation? In my opinion, it was possible to do without the interface.

Polymorphism could be achieved without using IDbCommand , but by casting classes to the base type.


I understand design principles like this:

If we need to describe only the contract, we choose the interface. This way we can make it possible to apply this contract without restricting the programmer in its implementation (the interface does not impose restrictions on inheritance).

If we have some kind of mandatory code (for example, the "template method" pattern) and we want to impose its use, we choose an abstract class. Here the programmer will be forced to inherit from it.

If there are no "impose" requirements, then we describe the contract as an interface and optionally can give birth to an abstract class (s) for "boilerplate code"

With regard to DbCommand – there is some implementation in the form of a bunch of attached attributes on properties and so on, which is common for SqlCommand and OleDbCommand , but the IDbCommand interface leaves freedom to those who do not need it.

In practice, hardly anyone will use IDbCommand , but an interface is preferable to describe a contract, so we have an interface (as a contract description) and an abstract class (as a base class that allows you to optionally use common functionality).

ps: these principles are for public code. In your own code, interfaces (abstract classes) should be created only when needed.

Scroll to Top