Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Complete return from base method

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

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

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

Currently I am looking at changing the void to bool and using that as a flow control, but I was wondering if there are any other design patterns I might be able to use.

like image 229
Talib Avatar asked May 28 '12 09:05

Talib


People also ask

What is C full form?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Why is C named so?

After language 'B', Dennis Ritchie came up with another language which was based upon 'B'. As in alphabets B is followed by C and hence he called this language as 'C'.


1 Answers

Is this an error "situation"? If so, just make it throw an exception, and don't catch the exception within the override.

If it's not an error situation, then using the return type does sound like a way forward, but it may not be suitable for your context - we don't really know what you're trying to achieve.

Another option is to use the template method pattern:

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

    protected abstract void DoConditionalAction();
}

If you don't want to make the base class abstract, you could make it a protected virtual method which does nothing in the base class and is overridden in the derived class where appropriate. Note that DoSomething is not virtual here.

If none of these options sounds appropriate, you'll need to provide us more concrete information about what you're trying to achieve.

like image 59
Jon Skeet Avatar answered Sep 28 '22 04:09

Jon Skeet