Force method to call base method from base class - c#

If i am creating method with "override" property, derived method will not call base method implementation automatically and i will need to call it manually using "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 string "A" and "B" will be written to console. So the question is how can i get rid of "base.Say();" line? So i want to force every derived method "Say" to call base method from base class. Is it possible? I am looking for any solutions, even if i will be forced to use other keywords

Although it is not possible to achieve this directly, you could get the same effect by writing your own method that is not virtual, which calls the virtual after performing some fixed operation:
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 inheriting from A and implementing SayImpl() would have A prepended to its printout.

Related

Insert code from child class method in middle of base class method [duplicate]

I have a base class and a class inheriting base. The base class has several virtual functions that the inherited class may override. However, the virtual functions in the base class has code that MUST to run before the inherited class overrides get called. Is there some way that I can call the base classes virtual functions first then the inherited class overrides. Without making a call to base.function().
I know I can simply make two functions, one that gets called, the other virtual. But is there a way I can keep the same names as well? I know I may need to change some things around.
class myBase
{
public virtual myFunction()
{ /* must-run code, Called first */ }
}
class myInherited : myBase
{
public override myFunction()
{ /* don't use base.myFunction();,
called from base.myFunction(); */ }
}
Similar question here.
C# doesn't have support for automatically enforcing this, but
you can enforce it by using the template method pattern. For example, imagine you had this code:
abstract class Animal
{
public virtual void Speak()
{
Console.WriteLine("I'm an animal.");
}
}
class Dog : Animal
{
public override void Speak()
{
base.Speak();
Console.WriteLine("I'm a dog.");
}
}
The trouble here is that any class inheriting from Animal needs to call base.Speak(); to ensure the base behavior is executed. You can automatically enforce this by taking the following (slightly different) approach:
abstract class Animal
{
public void Speak()
{
Console.WriteLine("I'm an animal.");
DoSpeak();
}
protected abstract void DoSpeak();
}
class Dog : Animal
{
protected override void DoSpeak()
{
Console.WriteLine("I'm a dog.");
}
}
In this case, clients still only see the polymorphic Speak method, but the Animal.Speak behavior is guaranteed to execute. The problem is that if you have further inheritance (e.g. class Dachshund : Dog), you have to create yet another abstract method if you want Dog.Speak to be guaranteed to execute.
A common solution that can be found in the .NET Framework is to split a method in a public method XXX and a protected, virtual method OnXXX that is called by the public method. For your example, it would look like this:
class MyBase
{
public void MyMethod()
{
// do something
OnMyMethod();
// do something
}
protected virtual void OnMyMethod()
{
}
}
and
class MyInherited : MyBase
{
protected override void OnMyMethod()
{
// do something
}
}
public abstract class BaseTemp
{
public void printBase() {
Console.WriteLine("base");
print();
}
public abstract void print();
}
public class TempA: BaseTemp
{
public override void print()
{
Console.WriteLine("TempA");
}
}
public class TempB: BaseTemp
{
public override void print()
{
Console.WriteLine("TempB");
}
}
There is no way to do what you're seeking other than the 2 ways you already named.
Either you make 2 functions in the base class, one that gets called and the other virtual.
Or you call base.functionName in the sub-class.
Not exactly. But I've done something similar using abstract methods.
Abstract methods must be overriden by derived classes. Abstract procs are virtual so you can be sure that when the base class calls them the derived class's version is called. Then have your base class's "Must Run Code" call the abstract proc after running. voila, your base class's code always runs first (make sure the base class proc is no longer virtual) followed by your derived class's code.
class myBase
{
public /* virtual */ myFunction() // remove virtual as we always want base class's function called here
{ /* must-run code, Called first */
// call derived object's code
myDerivedMustcallFunction();
}
public abstract myDerivedMustCallFunction() { /* abstract functions are blank */ }
}
class myInherited : myBase
{
public override myDerivedMustCallFunction()
{ /* code to be run in derived class here */ }
}
What do you think of this?
class myBase
{
public void myFunctionWrapper()
{
// do stuff that must happen first
// then call overridden function
this.myFunction();
}
public virtual void myFunction(){
// default implementation that can be overriden
}
}
class myInherited : myBase
{
public override void myFunction()
{
}
}

Force base class virtual method call inside of base class

Don't get me wrong: I do not want to force an overriding method to call the base class like already asked 1000...times before :)
I wondered if there is any way to force the call of the base class implementation of a method inside the base class.
Example:
using System;
public class Program
{
public static void Main()
{
var c = new SubClass();
c.CallInfo();
}
internal class BaseClass {
protected virtual void Info(){
Console.WriteLine("BaseClass");
}
internal virtual void CallInfo() {
this.Info();
}
}
internal class SubClass : BaseClass {
protected override void Info() {
Console.WriteLine("SubClass");
}
internal override void CallInfo() {
base.CallInfo();
}
}
}
Output obviously would be SubClass. Is there any way to force the CallInfo method of BaseClass to call its own Info method so that the output would be BaseClass?
By marking your Info() method as virtual you are specifically asking for this type of inheritance behaviour to occur.
If you want to ensure that a method call in your base class is not overridden, you'll need to use a non-virtual method, e.g.
internal class BaseClass {
protected virtual void Info(){
this.FinalInfo();
}
protected void FinalInfo() {
Console.WriteLine("BaseClass");
}
internal virtual void CallInfo() {
this.FinalInfo();
}
}
No, you can't do that. The purpose of virtual methods is that derived classes can override the implementation and that the implementation is used even when called it from base classes.
If that causes problems then the method you want to run should not be a virtual method.
This would work, while it won't force an implementation by a subclass like virtual it'll allow you to override it.
public class Program
{
public static void Main()
{
var c = new SubClass();
c.CallInfo();
}
internal class BaseClass
{
protected void Info()
{
Console.WriteLine("BaseClass");
}
internal virtual void CallInfo()
{
this.Info();
}
}
internal class SubClass : BaseClass
{
protected new void Info()
{
Console.WriteLine("SubClass");
}
internal override void CallInfo()
{
base.CallInfo();
}
}
}

How to call a base method that is declared as abstract override

In C# it's possible to mark a virtual method abstract to force inherited class to implement it.
class A
{
public virtual void Method()
{
Console.WriteLine("A method call");
}
}
abstract class B : A
{
// Class inherited from B are forced to implement Method.
public abstract override void Method();
}
I would like to call the A implementation of Method from a class inherited from B.
class C : B
{
public override void Method()
{
// I would like to call A implementation of Method like this:
// base.base.Method();
}
}
The best way I find to do this is to add a protected method "MethodCore" in A implementation and call it when needed.
class A
{
public virtual void Method()
{
MethodCore();
}
protected void MethodCore()
{
Console.WriteLine("A method call");
}
}
abstract class B : A
{
public abstract override void Method();
}
class C : B
{
public override void Method()
{
MethodCore();
}
}
Is there any other way to do this ?
The best way I find to do this is to add a protected method "MethodCore" in A implementation and call it when needed.
Yes. Since you can't call an abstract method using base, all possible solutions are going to require you to eventually call Method in A using an A instance.
That said, it looks like you are looking for a way to provide a default implementation of Method in B such that any subclass of B that does not implement the method should simply use the implementation present in A. A better solution would be to not mark Method as abstract in B. Instead, make Method in B redirect to Method in A using base.Method()
abstract class B : A {
// Class inherited from B are forced to implement Method.
public virtual void Method() {
base.Method()//calls Method in A
}
}
This way, any subclass of B that wants to call Method from A can simply say base.Method().

Call a virtual method from its overridden

In order to call the base virtual method from its overridden one, how should I define the instance?
Assume I have class Derived which extends Base class. I have a virtual method in Base which is overrided in class Derived.
Like this : Base instance = new Derived();
or like this: Derived instance = new Derived();
For sure I shall not use Base instance = new Based(); for it call the virtual methos and not its override.
Whether a method override calls the implementation of the base class does not depend on the type of variable you use. So, as soon as you add base.MethodName() to the implementation of the override, the first two ways you describe will be ok.
As you also mention, the third approach will not work as it does not call the overridden version of the method.
Here is a grotty way you can do that. You'll have to expose a method which calls base version. IMO don't do that. but... It is possible.
void Main()
{
B b = new B();
b.DoSomething();
b.CallAVersionDoSomething();
}
class A
{
public virtual void DoSomething()
{
Console.WriteLine("A DoSomething");
}
}
class B : A
{
public override void DoSomething()
{
Console.WriteLine("B DoSomething");
}
public virtual void CallAVersionDoSomething()
{
base.DoSomething();
}
}
Or if you want to expose it really you can expose another method in Base class which does the job for you. Here's how you go
class A
{
public virtual void DoSomething()
{
ActualDoSomething();
}
public void ActualDoSomething()
{
Console.WriteLine("A DoSomething");
}
}
class B : A
{
public override void DoSomething()
{
Console.WriteLine("B DoSomething");
}
}
and you can use instance.ActualDoSomething() which can't be overridden so you get base class version all the time.

Calling base class's virtual method from derived class instance

I would like to explain main problem with example.
public class BaseClass
{
public virtual void Add()
{
Console.WriteLine("Add call from BaseClass");
}
public virtual void Edit()
{
Console.WriteLine(" Edit call from BaseClass");
this.Get();
}
public virtual void Get()
{
Console.WriteLine(" Get call from BaseClass");
}
}
public class DerivedClass:BaseClass
{
public override void Add()
{
Console.WriteLine(" Add call from DerivedClass");
base.Edit();
}
public override void Edit()
{
Console.WriteLine(" Edit call from DerivedClass");
}
public override void Get()
{
Console.WriteLine(" Get call from DerivedClass");
}
}
And called like
DerivedClass d = new DerivedClass();
d.Add();
The result :
Add call from DerivedClass
Edit call from BaseClass
Get call from DerivedClass
But I want to get the result as :
Add call from DerivedClass
Edit call from BaseClass
Get call from BaseClass
When derived class calls its own Add method, Add method calls base class EDit method. When base class edit method called from derived class it calls get method of the derived class. but I want to call base class's get method.
How can I achieve this?
How can I achieve this?
If you don't want virtual dispatch then don't dispatch a virtual method. Dispatch a non-virtual method. That implies that a non-virtual method must exist, so let's write one. Then it becomes obvious how it must be called:
public class BaseClass
{
public virtual void Add() { ... }
public virtual void Edit() { this.BaseGet(); }
public virtual void Get() { this.BaseGet(); }
private void BaseGet() { ... }
}
That's how do to what you want, but the more important question here is why do you want to do this thing? There is probably a better way to design your class hierarchy, but without knowing more about what you are really trying to do, it is hard to advise you.

Categories