Coder Perfect

C# Multiple Inheritance

Problem

C# does not directly provide such a pattern since multiple inheritance is bad (it makes the code more difficult). However, having this skill would be useful at times.

For example, I can use interfaces and three classes to implement the missing multiple inheritance pattern:

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(); }
}

I have to update the class FirstAndSecond every time I add a method to one of the interfaces.

Is it possible, as in C++, to inject numerous existing classes into a single new class?

Is there a way to solve this problem with code generation?

Alternatively, it may look something like this (imaginary c# syntax):

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

So that when I change one of the interfaces, I don’t have to edit the class FirstAndSecond.

Perhaps a practical example would be more useful:

You already have a class (for example, a text-based TCP client based on ITextTcpClient) that you utilize in various places across your project. You now feel compelled to construct a class component that is easily available to Windows Forms developers.

You currently have two options, as far as I’m aware:

In both circumstances, work must be done per method rather than per class. Because we’ll require all of TextTcpClient and Component’s functions, combining them into one class would be the simplest solution.

To avoid conflicts, code generation may be used, with the result being changed later, however typing this by hand is a pain in the neck.

Asked by Martin

Solution #1

Instead of attempting to emulate Multiple Inheritance, consider simply utilizing composition. Interfaces can be used to specify which classes make up a composition; for example, ISteerable indicates a property of type SteeringWheel, IBrakable suggests a property of type BrakePedal, and so on.

After that, you may utilize C# 3.0’s Extension Methods feature to make invoking methods on such implied properties much easier, for example:

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();
    }
}

Answered by Chris Wenham

Solution #2

The.net Framework and C# MI hasn’t been implemented by CLR because they haven’t figured out how it would work with C#, VB.net, and the other languages, not because “it would make source more complex.”

MI is a valuable notion; nevertheless, there are still some unanswered concerns, such as: “What do you do when there are numerous shared base classes in various superclasses?”

MI only works and works well in Perl, which is the only language I’ve ever worked with. Net may introduce it in the future, but not now. The CLR already supports MI, but as I previously stated, there are no language structures for it beyond that.

You’ll have to make do with proxy objects and numerous interfaces till then:(

Answered by IanNorton

Solution #3

This is possible thanks to a C# post-compiler I created:

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> { }

The post-compiler can be used as a Visual Studio post-build-event:

You can use it like this in the same assembly:

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

You use it like this in another assembly:

var fas = new FirstAndSecond();
fas.FirstMethod();
fas.SecondMethod();

Answered by Jordão

Solution #4

You might have a single abstract base class that implements both IFirst and ISecond, and then only inherit from that.

Answered by Joel Coehoorn

Solution #5

Using the default implementation of interface members in C# 8, you may now practically have multiple inheritance:

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
}

Answered by Ludmil Tinkov

Post is based on https://stackoverflow.com/questions/178333/multiple-inheritance-in-c-sharp