Reputation: 9
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
Upvotes: 0
Views: 87
Reputation: 3651
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();
}
}
Upvotes: 1