Reputation: 3
I don't know if I have chosen a correct headline, but I do hope I have.
I am currently trying to get a better understand of methods in C#, and in doing so I thought that I'd make a simple BankAccount
example.
So, what I have is this:
class BankAccount
{
public string Name
{
get { return _Name; }
set { _Name = value; }
}
private string _Name;
public int Balance
{
get { return _Balance; }
set { _Balance = value; }
}
private int _Balance;
public BankAccount(string name)
{
Name = name;
Balance = 1000;
}
// deposit money
public int Deposit(int balance)
{
Balance += balance;
return Balance;
}
// withdraw money
public int WithDraw(int balance)
{
Balance -= balance;
return Balance;
}
// print to console
public void Print()
{
Console.WriteLine("Owner: " + Name
+ "\nYour current balance is: $" + Balance);
}
}
What I want to do is this:
if I call "deposit" in Main and pass it a value, I want the print method to show me the amount (same goes for "withdraw").
How do I achieve this? I have tried some controle statements, but I don't know how to do this correctly with methods that have parameters?
I hope that someone can shed some light on this issue of mine.
Upvotes: 0
Views: 127
Reputation: 2793
What you can do is overload the method to do more than one thing, for example you can create an overload that takes an int
(the balance being subtracted or added) and a string
saying which action happening, then you can have this method in the code along with the already existing one
public void Print(int balance, string action)
{
Console.WriteLine("Owner: " + Name
+ "\nYour current balance is: $" + Balance
+ "and you " + action + ": $" + balance);
}
This could be used by passing the string action
as "withdrew"
or "deposited"
depending on which method calls it.
Using this overload allows you to both output the original Print
method, if they want to know their balance but never withdrew or deposited, and the new version all depending on which parameters you pass
For more information on overloading see this MSDN page
Example Usage:
public int Deposit(int balance)
{
Balance += balance;
Print(balance, "deposited"); //prints current balance AND action that was completed
return Balance;
}
public void ShowBalance()
{
Print(); //Just prints current balance
}
Upvotes: 2