252

Since multiple inheritance is bad (it makes the source more complicated) C# does not provide such a pattern directly. But sometimes it would be helpful to have this ability.

For instance I'm able to implement the missing multiple inheritance pattern using interfaces and three classes like that:

public interface IFirst { void FirstMethod(); }
public interface ISecond { void SecondMethod(); }

public class First:IFirst 
{ 
    public void FirstMethod() { Console.WriteLine("First"); } 
}

public class Second:ISecond 
{ 
    public void SecondMethod() { Console.WriteLine("Second"); } 
}

public class FirstAndSecond: IFirst, ISecond
{
    First first = new First();
    Second second = new Second();
    public void FirstMethod() { first.FirstMethod(); }
    public void SecondMethod() { second.SecondMethod(); }
}

Every time I add a method to one of the interfaces I need to change the class FirstAndSecond as well.

Is there a way to inject multiple existing classes into one new class like it is possible in C++?

Maybe there is a solution using some kind of code generation?

Or it may look like this (imaginary c# syntax):

public class FirstAndSecond: IFirst from First, ISecond from Second
{ }

So that there won't be a need to update the class FirstAndSecond when I modify one of the interfaces.


EDIT

Maybe it would be better to consider a practical example:

You have an existing class (e.g. a text based TCP client based on ITextTcpClient) which you do already use at different locations inside your project. Now you feel the need to create a component of your class to be easy accessible for windows forms developers.

As far as I know you currently have two ways to do this:

  1. Write a new class that is inherited from components and implements the interface of the TextTcpClient class using an instance of the class itself as shown with FirstAndSecond.

  2. Write a new class that inherits from TextTcpClient and somehow implements IComponent (haven't actually tried this yet).

In both cases you need to do work per method and not per class. Since you know that we will need all the methods of TextTcpClient and Component it would be the easiest solution to just combine those two into one class.

To avoid conflicts this may be done by code generation where the result could be altered afterwards but typing this by hand is a pure pain in the ass.

Community
  • 1
  • 1
Martin
  • 10,738
  • 14
  • 59
  • 67
  • To the extent that this is not simply multiple inheritance in disguise, how is it less complicated? – harpo Oct 07 '08 at 13:08
  • Thinking about the new extension methods in 3.5 and the way it works (static member call generation), this might be one of the next .NET language evolution. – Larry Oct 07 '08 at 13:12
  • @NazarMerza: Link has changed. Now: [The Problem with Multiple Inheritance](http://nazar-merza.com/index.php/26-oop/49-the-problem-with-multiple-inheritance). – Craig McQueen Sep 11 '13 at 05:20
  • 36
    Don't let propaganda fool you. Your very example shows that multiple inheritance is useful and interfaces is just a workaround for the lack of it – Kemal Erdogan Sep 29 '13 at 16:00
  • 1
    I heard that C# does not do multiple inheritance, because Java did not do it, and Java does not do it, because C++ did it in a way that has some problems (when repeatedly inheriting). Look at the way that Eiffel does it. Unlike perl, python, and some others, but like C++, the order of inheritance does not matter (A inherits B and C ≡ A inherits C and B). Eiffel resolves multiple and repeated inheritance without drama most of the time. However when there is a conflict there is a compilation error. It then gives mechanisms to resolve the conflicts. – ctrl-alt-delor Jun 07 '16 at 19:13
  • if FirstAndSecond class do not inherit IFirst and ISecond interfaces, result would be the same why do all this extra interface thing? does any one have better scenario to understand MI concept using Interfaces? – Imdad Ali Aug 25 '16 at 20:27
  • I'm sure someone has already answered this, but composition is a good alternative. – byxor Apr 23 '17 at 14:59
  • 4
    Multiple inheritance is not bad, just that the creators of Java were too lazy to bake it in their programming language and that laziness was passed on to others that came after. C++ solved the multiple inheritance problem long before Java existed. – Carlos Jimenez Bermudez Aug 04 '20 at 13:50

13 Answers13

238

Consider just using composition instead of trying to simulate Multiple Inheritance. You can use Interfaces to define what classes make up the composition, eg: ISteerable implies a property of type SteeringWheel, IBrakable implies a property of type BrakePedal, etc.

Once you've done that, you could use the Extension Methods feature added to C# 3.0 to further simplify calling methods on those implied properties, eg:

public interface ISteerable { SteeringWheel wheel { get; set; } }

public interface IBrakable { BrakePedal brake { get; set; } }

public class Vehicle : ISteerable, IBrakable
{
    public SteeringWheel wheel { get; set; }

    public BrakePedal brake { get; set; }

    public Vehicle() { wheel = new SteeringWheel(); brake = new BrakePedal(); }
}

public static class SteeringExtensions
{
    public static void SteerLeft(this ISteerable vehicle)
    {
        vehicle.wheel.SteerLeft();
    }
}

public static class BrakeExtensions
{
    public static void Stop(this IBrakable vehicle)
    {
        vehicle.brake.ApplyUntilStop();
    }
}


public class Main
{
    Vehicle myCar = new Vehicle();

    public void main()
    {
        myCar.SteerLeft();
        myCar.Stop();
    }
}
Chris Wenham
  • 23,679
  • 13
  • 59
  • 69
  • 15
    That's the point though - an idea like this would ease composition. – Jon Skeet Oct 07 '08 at 13:15
  • Could you provide a link that describes the concept? – spoulson Oct 07 '08 at 13:15
  • 11
    Yes, but there are use cases where you really need the methods as part of the main object – David Pierre Oct 07 '08 at 14:34
  • 9
    Unfortunately member variable data is not accessible in extension methods so you have to expose them as internal or (ug) public, though I think composition by contract is the best way to solve multiple inheritance. – cfeduke Oct 10 '08 at 10:52
  • 4
    We might want to check if `myCar` has finished steering left before calling `Stop`. It might roll over if `Stop` applied while `myCar` is in excessive speed. :D – Devraj Gadhavi Jun 22 '15 at 13:09
  • 2
    Great answer. I know this is an older post, but I see an issue with composing a specialised class which combines multiple fields. Also the IDisposable pattern is a challenge to cater for. Maybe a topic for another post. – Kind Contributor Apr 23 '18 at 23:48
151

Since multiple inheritance is bad (it makes the source more complicated) C# does not provide such a pattern directly. But sometimes it would be helpful to have this ability.

C# and the .net CLR have not implemented MI because they have not concluded how it would inter-operate between C#, VB.net and the other languages yet, not because "it would make source more complex"

MI is a useful concept, the un-answered questions are ones like:- "What do you do when you have multiple common base classes in the different superclasses?

Perl is the only language I've ever worked with where MI works and works well. .Net may well introduce it one day but not yet, the CLR does already support MI but as I've said, there are no language constructs for it beyond that yet.

Until then you are stuck with Proxy objects and multiple Interfaces instead :(

Sylvain Defresne
  • 42,429
  • 12
  • 75
  • 85
IanNorton
  • 7,145
  • 2
  • 25
  • 28
  • 43
    The CLR doesn't support multiple implementation inheritance, only multiple interface inheritance (which is also supported in C#). – Jordão Jul 26 '10 at 02:05
  • 4
    @Jordão: For completeness sake: it is possible for compilers to create MI for their types in the CLR. It does have it's caveats, it isn't CLS compliant for example. For more information see this (2004) article http://blogs.msdn.com/b/csharpfaq/archive/2004/03/07/why-doesn-t-c-support-multiple-inheritance.aspx – dvdvorle Mar 01 '12 at 08:45
  • Turns out you can also do python's MI using IronPython – IanNorton Mar 01 '12 at 20:21
  • 2
    @MrHappy: Very interesting article. I've actually investigated some way of [Trait Composition](http://codecrafter.blogspot.com/2011/05/nroles-experiment-with-roles-in-c.html) for C#, take a look. – Jordão Mar 03 '12 at 03:32
  • @IanNorton Multiple inheritance do cause complexity. It is also mentioned here - http://blogs.msdn.com/b/csharpfaq/archive/2004/03/07/why-doesn-t-c-support-multiple-inheritance.aspx – Mandeep Janjua May 08 '12 at 05:11
  • @IanNorton During 2009 how can you claim that C# 4.x will have MI? Please stop misguiding people just based upon your own assumptions. – Mandeep Janjua May 08 '12 at 05:14
  • 11
    @MandeepJanjua I did not claim any such thing, I said 'may well introduce it' The fact remains that the ECMA standard CLR does provide the IL machinery for multiple inheritence, just that nothing makes use of it fully. – IanNorton May 08 '12 at 21:44
  • 1
    MI exists in C++ and personally I have never had a problem with it – bzim Feb 26 '17 at 19:35
  • 4
    FYI multiple inheritance is not bad, and doesn't make code that complicated. Just thought I'd mention it. – Dmitri Nesteruk Apr 07 '17 at 21:22
20

I created a C# post-compiler that enables this kind of thing:

using NRoles;

public interface IFirst { void FirstMethod(); }
public interface ISecond { void SecondMethod(); }

public class RFirst : IFirst, Role {
  public void FirstMethod() { Console.WriteLine("First"); }
}

public class RSecond : ISecond, Role {
  public void SecondMethod() { Console.WriteLine("Second"); }
}

public class FirstAndSecond : Does<RFirst>, Does<RSecond> { }

You can run the post-compiler as a Visual Studio post-build-event:

C:\some_path\nroles-v0.1.0-bin\nutate.exe "$(TargetPath)"

In the same assembly you use it like this:

var fas = new FirstAndSecond();
fas.As<RFirst>().FirstMethod();
fas.As<RSecond>().SecondMethod();

In another assembly you use it like this:

var fas = new FirstAndSecond();
fas.FirstMethod();
fas.SecondMethod();
Marcos Dimitrio
  • 6,651
  • 5
  • 38
  • 62
Jordão
  • 55,340
  • 13
  • 112
  • 144
6

You could have one abstract base class that implements both IFirst and ISecond, and then inherit from just that base.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • 1
    This is probably the best solution, but not necessarily the best idea :p – leppie Oct 07 '08 at 13:10
  • 1
    wouldn't you still have to edit the abstract class when you add methods to the interafces? – Rik Oct 07 '08 at 13:27
  • Rik: just how lazy are you, when you only have to do this once? – leppie Oct 07 '08 at 13:43
  • 3
    @leppie - "Every time I add a method to one of the interfaces I need to change the class FirstAndSecond as well." This part of the original question isn't addressed by this solution, is it? – Rik Oct 07 '08 at 14:00
  • 2
    You would have to edit the abstract class, but you NOT have to edit any other classes that depend on it. The buck stops there, rather than continuing to cascade to the entire collection of classes. – Joel Coehoorn Oct 07 '08 at 14:57
  • 2
    @JoelCoehoorn: I don't follow this answer... classes can implement multiple interfaces, so why do even need a abstract base class? I am not able to understand how would this solve the MI problem? – Hooman Bahreini Dec 03 '20 at 21:47
5

With C# 8 now you practically have multiple inheritance via default implementation of interface members:

interface ILogger
{
    void Log(LogLevel level, string message);
    void Log(Exception ex) => Log(LogLevel.Error, ex.ToString()); // New overload
}

class ConsoleLogger : ILogger
{
    public void Log(LogLevel level, string message) { ... }
    // Log(Exception) gets default implementation
}
Ludmil Tinkov
  • 555
  • 5
  • 4
  • 9
    Yes, but notice that, in the above, you would not be able to do `new ConsoleLogger().Log(someEception)` — it simply will not work, you'd have to explicitly cast your object to an `ILogger` to use the default interface method. So its usefulness is somewhat limited. – Dmitri Nesteruk Nov 18 '19 at 13:24
2

This is along the lines of Lawrence Wenham's answer, but depending on your use case, it may or may not be an improvement -- you don't need the setters.

public interface IPerson {
  int GetAge();
  string GetName();
}

public interface IGetPerson {
  IPerson GetPerson();
}

public static class IGetPersonAdditions {
  public static int GetAgeViaPerson(this IGetPerson getPerson) { // I prefer to have the "ViaPerson" in the name in case the object has another Age property.
    IPerson person = getPerson.GetPersion();
    return person.GetAge();
  }
  public static string GetNameViaPerson(this IGetPerson getPerson) {
    return getPerson.GetPerson().GetName();
  }
}

public class Person: IPerson, IGetPerson {
  private int Age {get;set;}
  private string Name {get;set;}
  public IPerson GetPerson() {
    return this;
  }
  public int GetAge() {  return Age; }
  public string GetName() { return Name; }
}

Now any object that knows how to get a person can implement IGetPerson, and it will automatically have the GetAgeViaPerson() and GetNameViaPerson() methods. From this point, basically all Person code goes into IGetPerson, not into IPerson, other than new ivars, which have to go into both. And in using such code, you don't have to be concerned about whether or not your IGetPerson object is itself actually an IPerson.

William Jockusch
  • 26,513
  • 49
  • 182
  • 323
2

In my own implementation I found that using classes/interfaces for MI, although "good form", tended to be a massive over complication since you need to set up all that multiple inheritance for only a few necessary function calls, and in my case, needed to be done literally dozens of times redundantly.

Instead it was easier to simply make static "functions that call functions that call functions" in different modular varieties as a sort of OOP replacement. The solution I was working on was the "spell system" for a RPG where effects need to heavily mix-and-match function calling to give an extreme variety of spells without re-writing code, much like the example seems to indicate.

Most of the functions can now be static because I don't necessarily need an instance for spell logic, whereas class inheritance can't even use virtual or abstract keywords while static. Interfaces can't use them at all.

Coding seems way faster and cleaner this way IMO. If you're just doing functions, and don't need inherited properties, use functions.

hydrix
  • 332
  • 2
  • 9
1

If you can live with the restriction that the methods of IFirst and ISecond must only interact with the contract of IFirst and ISecond (like in your example)... you can do what you ask with extension methods. In practice, this is rarely the case.

public interface IFirst {}
public interface ISecond {}

public class FirstAndSecond : IFirst, ISecond
{
}

public static MultipleInheritenceExtensions
{
  public static void First(this IFirst theFirst)
  {
    Console.WriteLine("First");
  }

  public static void Second(this ISecond theSecond)
  {
    Console.WriteLine("Second");
  }
}

///

public void Test()
{
  FirstAndSecond fas = new FirstAndSecond();
  fas.First();
  fas.Second();
}

So the basic idea is that you define the required implementation in the interfaces... this required stuff should support the flexible implementation in the extension methods. Anytime you need to "add methods to the interface" instead you add an extension method.

Amy B
  • 108,202
  • 21
  • 135
  • 185
1

Yes using Interface is a hassle because anytime we add a method in the class we have to add the signature in the interface. Also, what if we already have a class with a bunch of methods but no Interface for it? we have to manually create Interface for all the classes that we want to inherit from. And the worst thing is, we have to implement all methods in the Interfaces in the child class if the child class is to inherit from the multiple interface.

By following Facade design pattern we can simulate inheriting from multiple classes using accessors. Declare the classes as properties with {get;set;} inside the class that need to inherit and all public properties and methods are from that class, and in the constructor of the child class instantiate the parent classes.

For example:

 namespace OOP
 {
     class Program
     {
         static void Main(string[] args)
         {
             Child somechild = new Child();
             somechild.DoHomeWork();
             somechild.CheckingAround();
             Console.ReadLine();
         }
     }

     public class Father 
     {
         public Father() { }
         public void Work()
         {
             Console.WriteLine("working...");
         }
         public void Moonlight()
         {
             Console.WriteLine("moonlighting...");
         }
     }


     public class Mother 
     {
         public Mother() { }
         public void Cook()
         {
             Console.WriteLine("cooking...");
         }
         public void Clean()
         {
             Console.WriteLine("cleaning...");
         }
     }


     public class Child 
     {
         public Father MyFather { get; set; }
         public Mother MyMother { get; set; }

         public Child()
         {
             MyFather = new Father();
             MyMother = new Mother();
         }

         public void GoToSchool()
         {
             Console.WriteLine("go to school...");
         }
         public void DoHomeWork()
         {
             Console.WriteLine("doing homework...");
         }
         public void CheckingAround()
         {
             MyFather.Work();
             MyMother.Cook();
         }
     }


 }

with this structure class Child will have access to all methods and properties of Class Father and Mother, simulating multiple inheritance, inheriting an instance of the parent classes. Not quite the same but it is practical.

Yogi
  • 410
  • 4
  • 16
  • 2
    I disagree with the first paragraph. You only add the signatures of the methods you want in EVERY class to the interface. But you can add as many additional methods to any classes as you want. Also, there is a right click, extract interface which makes the job of extracting interfaces simple. Finally, your example is not in any way inheritance (multiple or otherwise), it is however a great example of composition. Alas, it would have more merit had you used interfaces to also demonstrate DI/IOC using constructor / property injection. While I wont vote down I don't think its a good answer sorry. – Francis Rodgers Dec 17 '14 at 19:25
  • 1
    Looking back at this thread a year later, I agree you can add as many methods as you want in the class without adding signature in the interface, however, this would make the interface incomplete. Besides, I was not able to find the right-click - extract interface in my IDE, maybe I was missing something. But, my bigger concern is, when you specify a signature in the interface, the inheriting classes must implement that signature. I think this is double work and could lead to duplication of codes. – Yogi Aug 08 '15 at 15:50
  • EXTRACT INTERFACE: right click over the class signature, then extract interface... in VS2015 same process **except** you must right click, then choose `Quick Actions and Refactorings...` this is a must know, it will save you a lot of time – Chef_Code Sep 26 '16 at 18:49
0

Multiple inheritance is one of those things that generally causes more problems than it solves. In C++ it fits the pattern of giving you enough rope to hang yourself, but Java and C# have chosen to go the safer route of not giving you the option. The biggest problem is what to do if you inherit multiple classes that have a method with the same signature that the inheritee doesn't implement. Which class's method should it choose? Or should that not compile? There is generally another way to implement most things that doesn't rely on multiple inheritance.

tloach
  • 8,009
  • 1
  • 33
  • 44
  • 8
    Please don't judge MI by C++, that's like judging OOP by PHP or automobiles by Pintos. That problem is easily solvable: in Eiffel, when you inherit from a class, you also have to specify which methods you want to inherit and you can rename them. No ambiguities there and no suprises either. – Jörg W Mittag Dec 13 '08 at 12:44
  • 2
    @mP: no, Eiffel provides true multiple implementation inheritance. Renaming doesn't mean loosing the inheritance chain, nor will it loose the castability of classes. – Abel Jul 19 '10 at 15:33
0

Since the question of multiple inheritance (MI) pops up from time to time, I'd like to add an approach which addresses some problems with the composition pattern.

I build upon the IFirst, ISecond,First, Second, FirstAndSecond approach, as it was presented in the question. I reduce sample code to IFirst, since the pattern stays the same regardless of the number of interfaces / MI base classes.

Lets assume, that with MI First and Second would both derive from the same base class BaseClass, using only public interface elements from BaseClass

This can be expressed, by adding a container reference to BaseClass in the First and Second implementation:

class First : IFirst {
  private BaseClass ContainerInstance;
  First(BaseClass container) { ContainerInstance = container; }
  public void FirstMethod() { Console.WriteLine("First"); ContainerInstance.DoStuff(); } 
}
...

Things become more complicated, when protected interface elements from BaseClass are referenced or when First and Second would be abstract classes in MI, requiring their subclasses to implement some abstract parts.

class BaseClass {
  protected void DoStuff();
}

abstract class First : IFirst {
  public void FirstMethod() { DoStuff(); DoSubClassStuff(); }
  protected abstract void DoStuff(); // base class reference in MI
  protected abstract void DoSubClassStuff(); // sub class responsibility
}

C# allows nested classes to access protected/private elements of their containing classes, so this can be used to link the abstract bits from the First implementation.

class FirstAndSecond : BaseClass, IFirst, ISecond {
  // link interface
  private class PartFirst : First {
    private FirstAndSecond ContainerInstance;
    public PartFirst(FirstAndSecond container) {
      ContainerInstance = container;
    }
    // forwarded references to emulate access as it would be with MI
    protected override void DoStuff() { ContainerInstance.DoStuff(); }
    protected override void DoSubClassStuff() { ContainerInstance.DoSubClassStuff(); }
  }
  private IFirst partFirstInstance; // composition object
  public FirstMethod() { partFirstInstance.FirstMethod(); } // forwarded implementation
  public FirstAndSecond() {
    partFirstInstance = new PartFirst(this); // composition in constructor
  }
  // same stuff for Second
  //...
  // implementation of DoSubClassStuff
  private void DoSubClassStuff() { Console.WriteLine("Private method accessed"); }
}

There is quite some boilerplate involved, but if the actual implementation of FirstMethod and SecondMethod are sufficiently complex and the amount of accessed private/protected methods is moderate, then this pattern may help to overcome lacking multiple inheritance.

grek40
  • 13,113
  • 1
  • 24
  • 50
0

If X inherits from Y, that has two somewhat orthogonal effects:

  1. Y will provide default functionality for X, so the code for X only has to include stuff which is different from Y.
  2. Almost anyplace a Y would be expected, an X may be used instead.

Although inheritance provides for both features, it is not hard to imagine circumstances where either could be of use without the other. No .net language I know of has a direct way of implementing the first without the second, though one could obtain such functionality by defining a base class which is never used directly, and having one or more classes that inherit directly from it without adding anything new (such classes could share all their code, but would not be substitutable for each other). Any CLR-compliant language, however, will allow the use of interfaces which provide the second feature of interfaces (substitutability) without the first (member reuse).

supercat
  • 77,689
  • 9
  • 166
  • 211
0

i know i know even though its not allowed and so on, sometime u actualy need it so for the those:

class a {}
class b : a {}
class c : b {}

like in my case i wanted to do this class b : Form (yep the windows.forms) class c : b {}

cause half of the function were identical and with interface u must rewrite them all

ariel
  • 9
  • 1
  • 1
    Your example doesn't depict multiple inheritance, so what problem are _you_ trying to solve? A true multiple inheritance example would show `class a : b, c` (implementing any necessary contract holes). Perhaps your examples are just over simplified? – M.Babcock Jan 24 '13 at 05:27