Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Abstract function with implementation possible?

Is there a way to add a virtual function that must be overridden by all inherited classes? So actually the combination of virtual and abstract? I have a situation where each inherited class must do some specific processing before some generic code is executed. Virtual functions doesn't work because they do not ensure the inherited classes override them. And abstract function can't have a default implementation. Currently my workaround is to implement another protected function in the base class which contains the common/generic code and is called in the overridden abstract function

like image 523
Tin Avatar asked Jul 22 '11 05:07

Tin


People also ask

What is the full name of C?

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 is a powerful general-purpose programming language. It can be used to develop software like operating systems, databases, compilers, and so on.

Why is C named so?

Quote from wikipedia: "A successor to the programming language B, C was originally developed at Bell Labs by Dennis Ritchie between 1972 and 1973 to construct utilities running on Unix." The creators want that everyone "see" his language. So he named it "C".


2 Answers

It is not possible to have a method that is both abstract and virtual.

If possible, you can split your method in a "before" and "after" part:

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 if DoCommonWork was really called in DoWork using a thread-local field if necessary.

However, I'd probably go with making the method virtual. If the derived class doesn't want to add anything to the common part, it shouldn't have to:

public virtual void DoWork() { ... }

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

like image 169
dtb Avatar answered Oct 19 '22 12:10

dtb


I think you might be looking for a template method: Implement a method in your base class that calls an abstract method as part of its implementation. Derived classes then can implement the abstract method, but this allows the base class to do "some specific processing" before this method is executed.

like image 3
BrokenGlass Avatar answered Oct 19 '22 10:10

BrokenGlass