C # Abstract function with implementability?

Is there a way to add a virtual function that needs to be overridden by all inherited classes? So is it really a combination of virtual and abstract? I have a situation where every inherited class needs to do some processing before executing some common code. Virtual functions do not work because they do not guarantee that inherited classes override them. And an abstract function cannot have a default implementation. Currently, my workaround is to implement another protected function in the base class that contains the common / common code and is called in an overridden abstract function

+7
source share
3 answers

It is impossible to have a method that is abstract and virtual.

If possible, you can split your method into “before” and “after” parts:

public void DoWork() { DoBeforeWork(); DoCommonWork(); DoAfterWork(); } protected abstract void DoBeforeWork(); protected abstract void DoAfterWork(); private void DoCommonWork() { ... } 

Otherwise, your workaround with a second protected method is a very good idea:

 public void DoWork() { DoActualWork(); } protected abstract void DoActualWork(); // expected to call DoCommonWork protected void DoCommonWork() { ... } 

You can check whether DoCommonWork is actually called in DoWork using a thread-field.

However, I would probably make the method virtual. If the derived class does not want to add anything to the common part, it does not need to:

 public virtual void DoWork() { ... } 

Again, you can check if the common part was actually called.

+11
source

I think you can find a template method : implement a method in a base class that calls an abstract method as part of its implementation, Derived classes can then implement an abstract method, but this allows the base class to perform “specific processing” before this method is executed .

+2
source

My suggestion is to split the base class into two: classes of one abstract and one concrete sealed.

Example

I assume that you have a base class that looks like this:

 public class BaseClass { public void DoProcessing() { // this method must be overriden in each subclass } } 

Let me break it into two:

 public abstract class BaseClass { protected abstract DoProcessingImlementation(); public void DoProcessing() { // here you can add program logic or just call overridden implementation DoProcessingImplementation(); } } public sealed class DefaultBaseClassImplementation : BaseClass { public override DoProcessingImlementation() { // default implementation of method } } 

With this design, if you need to implement a new processing logic, you inherit a new class from BaseClass , and since it is abstract, you must implement the DoSomethigImplementation method. To access the default processing logic, you must use an instance of the DefaultBaseClassImplementation class. And the fact that DefaultBaseClassImplementation sealed will not allow you to inherit from the wrong class.

0
source

All Articles