C # - full return from the base method

I have a virtual base void Action() method that is overridden in a derived class.

The first step in the action is to call base.Action() . If a situation arises in the base method, I do not want the rest of the derived method to be processed.

I want to know if there is a keyword or design template that will allow me to exit the derived method from the base method.

I am currently looking at changing void on bool and using this as a flow control, but I was wondering if there are other design templates that I could use.

+6
source share
3 answers

Do not use it with void return type, but you can do, say bool

 public class Base { public virtual bool Action() { .. return boolean-value. } } public class Child : Base { public override bool Action() { if(!base.Action()) return false; .... return boolean-value; } } 

Or, if it is an exception, call an exception like the others.

+3
source

Is this a β€œsituation” error? If so, just make it throw an exception and don't catch the exception in the override.

If this is not a mistake, then using the return type sounds like a way forward, but it may not be suitable for your context - we really do not know what you are trying to achieve.

Another option is to use a template template:

 public abstract class FooBase { public void DoSomething() { DoUnconditionalActions(); if (someCondition) { DoConditionalAction(); } } protected abstract void DoConditionalAction(); } 

If you do not want to abstract the base class, you can make it a protected virtual method that does nothing in the base class and is redefined in the derived class where necessary. Please note that DoSomething is not virtual here.

If none of these options apply, you need to provide us with more specific information about what you are trying to achieve.

+3
source

Throw an exception in the base method. He will exit every method that called him until he is captured.

0
source

Source: https://habr.com/ru/post/916823/


All Articles