0

I am trying to overcome the lack of Multiple Inheritance support in C# and be able to inherit (almost inherit) a few classes using Method Extensions:

public interface IA
{
   // nothing 
}
public static class A
{
   public static void FunctionA( this IA a)
   {
     // do something
   }
}

public interface IB
{
   // nothing 
}
public static class B
{
   public static void FunctionB( this IB b)
   {
     // do something
   }
}

public class Derived : IA, IB
{
     // members 
}

// main code
Derived myDerivedobj = new Derived();
myDerivedobj.FunctionA(); // Call Function A inherited from Class A
myDerivedobj.FunctionB(); // Call Function B inherited from Class B

Though this code works and I am able to utilize the functions exposed by Class A and Class B in my derived class, is this the proper way to achieve it?

Thanks

Nex Gen
  • 9
  • 1
  • I don't know what you mean by 'proper', but it is definitely a commonly used method. Also: https://stackoverflow.com/q/2456154/302248 – Sach Aug 24 '17 at 18:54
  • If your interfaces don't actually have any members then those two functions can just accept `object` instances, and there's no need for interfaces at all. – Servy Aug 24 '17 at 19:41

1 Answers1

1

Another way is to use interface to expose methods (instead of extensions). And use aggregation and DI to avoid code duplication, by that I mean something like:

public interface IA
{
   void FunctionA(); 
}
public interface IB
{
   void FunctionB();
}
public class A : IA
{
    // actual code
}
public class B : IB
{
    // actual code
}

public class Derived : IA, IB
{
    private IA _a;
    private IB _b;

    public Derived(IA a, IB b)
    {
        _a = a;
        _b = b;
    }
    public void FunctionA()
    {
        _a.FunctionA();
    }
    public void FunctionB()
    {
        _b.FunctionB();
    }
}
ASpirin
  • 3,601
  • 1
  • 23
  • 32