This question already has an answer here:
I am very new to c# and I am working through a textbook. The textbook shows this piece of code:
public class BankAccount
{
// Bank accounts start at 1000 and increase sequentially.
public static int _nextAccountNumber = 1000;
// Maintain the account number and balance for each object.
public int _accountNumber;
public decimal _balance;
// Constructors
public BankAccount() : this(0)
{
}
public BankAccount(decimal initialBalance)
{
_accountNumber = ++_nextAccountNumber;
_balance = initialBalance;
}
// more methods...
I am having trouble understanding this:
public BankAccount() : this(0)
{
}
It looks like the syntax for inheritance, but I guess it isn't because this(0)
is not a class. And I don't think it would make logical sense to inherit from the same class that is being used. It is probably a constructor and the syntax is confusing me.
What does this(0)
mean? Why use this
, is there another way to write it?
Would this be the same?:
public BankAccount()
{
BankAccount(0);
}
I understand the following:
public BankAccount(decimal initialBalance)
{
_accountNumber = ++_nextAccountNumber;
_balance = initialBalance;
}
It appears to be a constructor that accepts a balance value, and sets the account number.
My guess would be that this(0)
is really just executing BankAccount(0)
. If this is true, why bother writing two constructors? BankAccount(0)
seems to work fine.
Can someone explain what this
is in a simple way (new to c#; coming from python)?
In the context here, it means "when the constructor
public BankAccount()
is called, execute the other constructor, matching the signature. The0
matchespublic BankAccount(decimal initialBalance)
, causing that constructor to be called as well.The keyword
this
can be applied in other context as well, but it always refers to the current instance of the class. This also means it's not present in static classes, since they aren't instantiated.Your guess is correct,
this(0)
is calling theBankAccount(decmial)
constructor.The reason you might create two is to give the consumer of your class a choice. If they have a value they can use the
BackAccount(decimal)
constructor, if they don't care they can save themselves a few seconds by using theBankAccount()
constructor and it will initialize the balance to a reasonable value. In addition, if you ever wanted to change the default you can do so in one place.It means that the constructor calls another constructor of the same class. Which constructor is called depends on int signature.
In this case
this(0)
will call the only matching constructor,BankAccount(decimal initialBalance)
, since0
can be passed asdecimal
.