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
Abstract classes do not support multiple inheritance.
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.
No, as multiple inheritance is not supported in C#.
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)
// {
// }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With