You can define an abstract
class with “default” behavior by declaring a method as virtual
and overriding it in derived classes.
A derived class is not forced to override a virtual
method in an abstract base class. If the method is not overridden, the behavior defined in the abstract class is used. Overriding the method can be used to replace the behavior entirely, or implement additional functionality (on top of calling base.MethodName()
).
Unless I’ve misunderstood your question, this pattern should work for your scenario.
dotnetfiddle link: https://dotnetfiddle.net/7JQQ6I
Abstract base class:
public abstract class Plugin
{
public virtual string Output()
{
return "Default";
}
}
A derived class that uses the default implementation, and one that overrides it:
public class BoringPlugin : Plugin
{
public override string Output()
{
return base.Output();
}
}
public class ExcitingPlugin : Plugin
{
public override string Output()
{
return "No boring defaults here!";
}
}
Test result:
public static void Main()
{
var boring = new BoringPlugin();
Console.WriteLine(boring.Output());
var exciting = new ExcitingPlugin();
Console.WriteLine(exciting.Output());
}
Default
No boring defaults here!
solved Is this the correct way to use a inheritence?