How can I simulate multiple inheritance in C# without using interfaces. I do believe, interfaces abilityes are not intended for this task. I'm looking for more 'design pattern' oriented way.
-
2Is this for some real project or is it an academic question? If it is for a concrete project please provide more details.Darin Dimitrov– Darin Dimitrov2010-10-03 08:28:48 +00:00Commented Oct 3, 2010 at 8:28
-
@Darin Dimitrov, no It is not for concreate project.kofucii– kofucii2010-10-03 08:33:53 +00:00Commented Oct 3, 2010 at 8:33
-
5artima.com/designtechniques/compoinhP.html Composition versus Inheritance, by Bill Venners.rwong– rwong2010-10-03 08:35:23 +00:00Commented Oct 3, 2010 at 8:35
-
4There are two main uses for multiple implementation inheritance. (1) expressing complex "is a kind of" relationships in a world where hierarchies do not cleanly partition everything into one category. Like a Submarine is both a Watercraft and a MilitaryVehicle. (2) Re-using implementation detail functionality from multiple sources. Which of the two, if either, are you primarily interested in? Is there some third aspect of multiple inheritance that you are particularly keen on?Eric Lippert– Eric Lippert2010-10-04 15:35:34 +00:00Commented Oct 4, 2010 at 15:35
5 Answers
Like Marcus said using interface + extension methods to make something like mixins is probably your best bet currently.
also see: Create Mixins with Interfaces and Extension Methods by Bill Wagner Example:
using System;
public interface ISwimmer{
}
public interface IMammal{
}
class Dolphin: ISwimmer, IMammal{
public static void Main(){
test();
}
public static void test(){
var Cassie = new Dolphin();
Cassie.swim();
Cassie.giveLiveBirth();
}
}
public static class Swimmer{
public static void swim(this ISwimmer a){
Console.WriteLine("splashy,splashy");
}
}
public static class Mammal{
public static void giveLiveBirth(this IMammal a){
Console.WriteLine("Not an easy Job");
}
}
prints splasshy,splashy Not an easy Job
Comments
Multiple inheritance in a form of a class is not possible, but they may be implemented in multi-level inheritance like:
public class Base {}
public class SomeInheritance : Base {}
public class SomeMoreInheritance : SomeInheritance {}
public class Inheriting3 : SomeModeInheritance {}
As you can see the last class inherits functionality of all three classes:
Base,SomeInheritanceandSomeMoreInheritance
But this is just inheritance and doing it this way is not good design and just a workaround. Interfaces are of course the preferred way of multiple inherited implementation declaration (not inheritance, since there's no functionality).
1 Comment
ECMA-334, § 8.9 Interfaces
...
Interfaces can employ multiple inheritance.
So for as far C# (limited) support of 'multiple inheritance' goes, interfaces are the official way.