Using the return value of a base class method?

I have a method in my base class that returns bool, and I want this bool to determine what happens with the same overridden method in my derived class.

Base:

public bool Debt(double bal) { double deb = 0; bool worked; if (deb > bal) { Console.WriteLine("Debit amount exceeds the account balance – withdraw cancelled"); worked = false; } else bal = bal - deb; worked = true; return worked; } 

Derivative

 public override void Debt(double bal) { // if worked is true do something } 

Note that bal comes from the constructor I made earlier

+6
source share
4 answers

You can call the base class method with the base keyword:

 public override void Debt(double bal) { if(base.Debt(bal)) DoSomething(); } 

As stated in the comments above, you need to either make sure that the base class has a virtual method with the same signature (return type and parameters), or remove the override keyword from the receiver class.

+10
source
 if(base.Debt(bal)){ // do A }else{ // do B } 

base refers to the base class. So base.X refers to X in the base class.

+2
source

Call base method:

 public override void Debt(double bal) { var worked = base.Debt(bal); //Do your stuff } 
+2
source

As several others have already been mentioned, you can use base.Debt(bal) to call the base class method. I also noticed that your base class method was not declared as virtual. C # methods are NOT virtual by default, so you will not override it in a derived class unless you specify it as virtual in the base class.

 //Base Class class Foo { public virtual bool DoSomething() { return true; } } // Derived Class class Bar : Foo { public override bool DoSomething() { if (base.DoSomething()) { // base.DoSomething() returned true } else { // base.DoSomething() returned false } } } 

Here is what msdn has to say about virtual methods

+1
source

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


All Articles