I have a bankAccount object I’d like to increment using the constructor. The objective is to have it increment with every new object the class instantiates.
Note: I’ve overriden the ToString() to display the accountType and accountNumber;
Here is my code:
public class SavingsAccount
{
private static int accountNumber = 1000;
private bool active;
private decimal balance;
public SavingsAccount(bool active, decimal balance, string accountType)
{
accountNumber++;
this.active = active;
this.balance = balance;
this.accountType = accountType;
}
}
Why is it that when I plug this in main like so:
class Program
{
static void Main(string[] args)
{
SavingsAccount potato = new SavingsAccount(true, 100.0m, "Savings");
SavingsAccount magician = new SavingsAccount(true, 200.0m, "Savings");
Console.WriteLine(potato.ToString());
Console.WriteLine(magician.ToString());
}
}
The output I get does not increment it individually i.e.
savings 1001
savings 1002
but instead I get:
savings 1002
savings 1002
How do I make it to be the former and not the latter?
Because a static variable is shared among all instances of the class. What you want is a static variable to keep the global count and a non-static variable to save the current count at the time of instantiation. Change your code above to:
And then in your ToString() overload you should print myAccountNumber instead of the static variable.