Trying to add with method, believe something is not instantiating

When I type in the textbox, I am wanting it to add the numbers, instead if I type (for example) 12, and click deposit again, it only shows 12. I think this is because it seems to think thats its 0 plus 12 everytime. Something doesnt seem to be instantiating correctly. I think. Can anyone point out what I am doing incorrectly?

namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }

    private void btn_deposit_Click(object sender, EventArgs e)
    {
        double input;
        input = double.Parse((putin.Text));
        BankAccount a = new BankAccount(input);
        aMtBox.Text = a.AccountBalance.ToString();
    }
}

public class BankAccount
{
    private double num1;
    private double accountBalance;

    public BankAccount(double input)
    {
        num1 = input;
        Deposit();
    }

    public double Num1
    {
        set {num1 = value;}
        get {return num1;}}

    public double AccountBalance
    {
        get {return accountBalance;}
        set {accountBalance = value;}}

    public void Deposit()
    {
        accountBalance = accountBalance + num1;
    }
}
}
Jon Skeet
people
quotationmark

You're creating a new instance of BankAccount each time the button is clicked - so accountBalance will be 0.0 (the default value for a field of type double). How did you expect it to "know" about the previous balance?

It's entirely possible that you should have an instance variable of type BankAccount in your form. You should also consider what the num1 instance variable in BankAccount is meant to represent. The name certainly doesn't tell us anything. It feels like it should actually just be a parameter to the Deposit method.

Additionally, for currency values you should never use double - use either decimal, or an integer type to represent the number of cents (or pence, or whatever). You don't want to get into the normal binary floating point issue.

At this point, your method would become something like:

// I hate the VS-generated event names, but...
private void btn_deposit_Click(object sender, EventArgs e)
{
    // TODO: Use decimal.TryParse, and handle invalid input cleanly.
    decimal newDeposit = decimal.Parse(putin.Text);
    account.Deposit(newDeposit);
    aMtBox.Text = account.AccountBalance.ToString();
}

people

See more on this question at Stackoverflow