Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a baseclass method return value?

I have a method in my baseclass that returns a bool and I want that bool to determine what happens to 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;
    }

Derived

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

    }

Note that bal comes from a constructor I made earlier

like image 767
TheAce Avatar asked Apr 30 '13 16:04

TheAce


People also ask

How to return a value from a class java?

You declare a method's return type in its method declaration. Within the body of the method, you use the return statement to return the value. Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so.

What is base class in C#?

base (C# Reference) A base class access is permitted only in a constructor, an instance method, or an instance property accessor. It is an error to use the base keyword from within a static method. The base class that is accessed is the base class specified in the class declaration.

Can base class access derived class properties?

// As base-class pointer cannot access the derived class variable.


3 Answers

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

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

}

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

like image 155
PHeiberg Avatar answered Oct 22 '22 09:10

PHeiberg


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.

like image 2
Julián Urbano Avatar answered Oct 22 '22 07:10

Julián Urbano


Call the base method:

public override void Debt(double bal)
{
    var worked = base.Debt(bal);
    //Do your stuff
}
like image 2
Dave Zych Avatar answered Oct 22 '22 08:10

Dave Zych