Pseudo-multiple inheritance with extension methods on interfaces in C #?

A similar question, but not quite the same

I thought that using extension methods in the same namespace as the interface, you can get a similar effect for multiple inheritance, since you do not need to duplicate code that implements the same interface in 10 different classes.

What are some of the disadvantages of this? I think the pros are pretty obvious, these are the cons that usually come back to bite you later.

One of the drawbacks that I see is that extension methods cannot be virtual, so you have to be sure that you really want them to be implemented the same way for each instance.

+6
multiple-inheritance extension-methods dry
source share
2 answers

The problem that I see with the ability to create an interface using extension methods is that you no longer implement the interface and therefore cannot use this object as an interface type.

Let's say I have a method that takes an object of type IBar. If I implement the IBar interface in the Foo class using extension methods, then Foo is not derived from IBar and cannot be interchanged with it (Liskov replacement principle). Of course, I get the behavior that I want to add to Foo, but I will lose the most important aspect of creating interfaces in the first place - the ability to define an abstract contract that can be implemented in various ways by different classes so that dependent classes do not need to know about specific implementations.

If I needed multiple inheritance (and until now I lived without it) bad enough, I would prefer to use composition to minimize the amount of code duplication.

+4
source share

A decent way to think about this is that instance methods are something performed by the object, while extension methods are something done for the object. I am pretty sure that the Framework Design Guide says that you should implement the instance method whenever possible.

The interface announces, "I care about using this function, but not how it is done." This leaves implementers free to choose how. It separates the intent, the public API, from the mechanism, the class with specific code.

Since this is the main advantage of interfaces, implementing them completely as extension methods seems to have exceeded their goal. Even IEnumerable<T> has an instance method.

Change In addition, objects are designed to work with the data that they contain. Extension methods can only see the public API of the object (since these are only static methods); you will need to set all the state of the object for it to work (OO no-no).

+1
source share

All Articles