Force method to call a base method from a base class
If I create a method with an "override" property, the derived method will not automatically call the implementation of the base method, and I will need to call it manually using the "base" keyword like this:
public class A
{
public virtual void Say()
{
Console.Write("A");
}
}
public class B : A
{
public override void Say()
{
base.Say();
Console.Write("B");
}
}
So, only in this case lines "A" and "B" will be written to the console. So the question is, how can I get rid of "base.Say ()"; line? Therefore, I want each "Say" derived method to call the base method from the base class. Is it possible? I am looking for any solutions, even if I have to use other keywords
There is no way to achieve this directly, you can get the same effect by writing your own non-virtual method that calls the virtual machine after some fixed operation has been performed:
public class A
{
public void Say()
{
Console.Write("A");
SayImpl();
}
protected virtual void SayImpl()
{
// Do not write anything here:
// for the base class the writing is done in Say()
}
}
public class B : A
{
protected override void SayImpl()
{
Console.Write("B");
}
}
Now any class that inherits from A
and implements SayImpl()
would A
have appended to its listing.