Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Similar question but not quite the same thing

I was thinking that with extension methods in the same namespace as the interface you could get a similar effect to multiple inheritance in that you don't need to have duplicate code implementing the same interface the same way in 10 different classes.

What are some of the downsides of doing this? I think the pros are pretty obvious, it's the cons that usually come back to bite you later on.

One of the cons I see is that the extension methods can't be virtual, so you need to be sure that you actually do want them implemented the same way for every instance.

like image 705
Davy8 Avatar asked May 30 '09 14:05

Davy8


2 Answers

The problem that I see with building interface capability via extension methods is that you are no longer actually implementing the interface and so can't use the object as the interface type.

Say I have a method that takes an object of type IBar. If I implement the IBar interface on class Foo via extension methods, then Foo doesn't derive from IBar and can't be used interchangeably with it (Liskov Substitution principle). Sure, I get the behavior that I want added to Foo, but I lose the most important aspect of creating interfaces in the first place -- being able to define an abstract contract that can be implemented in a variety of ways by various classes so that dependent classes need not know about concrete implementations.

If I needed multiple inheritance (and so far I've lived without it) badly enough, I think I'd use composition instead to minimize the amount of code duplication.

like image 57
tvanfosson Avatar answered Oct 11 '22 09:10

tvanfosson


A decent way to think about this is that instance methods are something done by the object, while extension methods are something done to the object. I am fairly certain the Framework Design Guidelines say you should implement an instance method whenever possible.

An interface declares "I care about using this functionality, but not how it is accomplished." That leaves implementers the freedom to choose the how. It decouples the intent, a public API, from the mechanism, a class with concrete code.

As this is the main benefit of interfaces, implementing them entirely as extension methods seems to defeat their purpose. Even IEnumerable<T> has an instance method.

Edit: Also, objects are meant to act on the data they contain. Extension methods can only see an object's public API (as they are just static methods); you would have to expose all of an object's state to make it work (an OO no-no).

like image 38
Bryan Watts Avatar answered Oct 11 '22 09:10

Bryan Watts