Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate multiple inheritance without interfaces?

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.

like image 262
kofucii Avatar asked Nov 02 '25 12:11

kofucii


2 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

like image 95
Roman A. Taycher Avatar answered Nov 04 '25 01:11

Roman A. Taycher


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,
  • SomeInheritance and
  • SomeMoreInheritance

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).

like image 20
Robert Koritnik Avatar answered Nov 04 '25 03:11

Robert Koritnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!