Set multiple base classes

Asked by At

I have a problem. I am using my MainActivity.cs as a FragmentActivity now, but I also need it to be a AppCompatActivity. Now when I try this:

public class MainActivity : FragmentActivity, AppCompatActivity

It gives the error:

Class 'MainActivity' cannot have multiple base classes: 'FragmentActivity' and 'AppCompatActivity'

But I need both, so how can I fix this?

1 Answers

4
Alex On Best Solutions

C# does not support multiple base classes, but allows to implement multiple interfaces. And composition is legal too.

Do it like this:

class A
{
    public void DoAStuff() { }
}

class B
{
    public void DoBStuff() { }
}

class C
{
    private readonly A a;
    private readonly B b;

    public C(A a, B b) => (this.a, this.b) = (a, b);

    public void DoAStuff() => a.DoAStuff();

    public void DoBStuff() => b.DoBStuff();

    public static implicit operator A(C c) => c.a;

    public static implicit operator B(C c) => c.b;
}

Note, you will be able to cast C to A and B implicitly like

C c = new C(new A(), new B());
c.DoAStuff();
c.DoBStuff();
A a = c;
a.DoAStuff();
B b = c;
b.DoBStuff();

but

new[] { new C(new A(), new B()) }.Cast<B>().ToArray()

will throw System.InvalidCastException.

Use

new[] { new C(new A(), new B()) }.Select(i => (B)i).ToArray();

If FragmentActivity and AppCompatActivity implement interfaces do it like this:

interface IA
{
    void DoAStuff();
}

class A : IA
{
    public void DoAStuff() { }
}

interface IB
{
    void DoBStuff();
}

class B : IB
{
    public void DoBStuff() { }
}

class C : IA, IB
{
    private readonly IA a;
    private readonly IB b;

    public C(IA a, IB b) => (this.a, this.b) = (a, b);

    public void DoAStuff() => a.DoAStuff();

    public void DoBStuff() => b.DoBStuff();
}

In this case any casting will work fine.