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

2
  • I don't know what you mean by 'proper', but it is definitely a commonly used method. Also: stackoverflow.com/q/2456154/302248 Commented Aug 24, 2017 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. Commented Aug 24, 2017 at 19:41

1 Answer 1

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();
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Why not decorators?
This is a step from the question example to decorators

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.