Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net Multiple inheritance from abstract classes

it is possible to implement this functionality? I've two abstract classes, and i want to force a third class to implement all the abstract methods in the two classes

public abstract class A
{
    private void MethodA()
    {
        var fool = Prop*2;
    }
    public abstract int Prop { get; }
}
public abstract class B
{
    private void MethodB()
    {
        //.... 
        SomeMethod();
        //....
    }
    public abstract void SomeMethod();
}

public class C: A, B
{
    public int Prop { .... }
    public void SomeMethod { .... }
}

The main problem here is that the implemented final class methods are then used in base abstract classes, and this cannot be achieved with interfaces. So there is no a workaround?

I've read many similar q/a but nothing responding to my problem. Thanks

like image 979
ʞᴉɯ Avatar asked Oct 02 '12 16:10

ʞᴉɯ


People also ask

Can we do multiple inheritance with abstract classes C#?

Abstract classes do not support multiple inheritance.

Can we have multiple inheritance in abstract class?

This is not allowed because you can do more than this with abstract classes. It wouldn't make sense to allow multiple inheritance, provided you only used an abstract class when you could have used an interface.

Can you extend more than one abstract class C#?

No, as multiple inheritance is not supported in C#.


1 Answers

As of C# 8.0 on .NET Core 3.0, C# supports default implementations for Interface members.

public interface ILight
{
    void SwitchOn();
    void SwitchOff();
    bool IsOn();
}

// Basic Implementation
public class OverheadLight : ILight
{
    private bool isOn;
    public bool IsOn() => isOn;
    public void SwitchOff() => isOn = false;
    public void SwitchOn() => isOn = true;

    public override string ToString() => $"The light is {(isOn ? "on" : "off")}";
}

// Interface with default implementation
public interface ITimerLight : ILight
{
    // defines default implementation
    public async Task TurnOnFor(int duration)
    {
        Console.WriteLine("Using the default interface method for the ITimerLight.TurnOnFor.");
        SwitchOn();
        await Task.Delay(duration);
        SwitchOff();
        Console.WriteLine("Completed ITimerLight.TurnOnFor sequence.");
    }
}

// Implementation with interface
public class OverheadLight : ITimerLight
{
    private bool isOn;
    public bool IsOn() => isOn;
    public void SwitchOff() => isOn = false;
    public void SwitchOn() => isOn = true;

    public override string ToString() => $"The light is {(isOn ? "on" : "off")}";

    // Automatically gets the interface implementation
    //
    // To provide your own implementation: (no use of override)
    // public async Task TurnOnFor(int duration)
    // {
    // }
}
like image 144
MitsakosGR Avatar answered Oct 22 '22 03:10

MitsakosGR